How does this solution of the subset sum problem‍​​ work?

What is the best to way to explain the solution of subset sum problem with negative numbers?

  • P. The Subset Sum problem takes as input a set X = {x1, x2 ,…, xn} of n integers and another integer K. The problem is to check if there exists a subset X' of X whose elements sum to K and finds the subset if there’s any. For example, if X = {5, 3, 11, 8, 2} and K = 16 then the answer is YES since the subset X' = {5, 11} has a sum of 16. Implement an algorithm for Subset Sum whose run time is at least O(nK). What if my array holds negative values? How should I solve it? http://en.wikipedia.org/wiki/Subset_sum_problem

  • Answer:

    It does not matter whether array contains only positive values or only negative values or a mix of positive and negative values. We use the same method irrespective of data values. However care should be taken in giving the constant K( required subset sum). No point in giving a -ve K if all array elements are positive and vice versa.

Gadiraju Venkata Padma Raju at Quora Visit the source

Was this solution helpful to you?

Other answers

Suppose we have the input set X={x1, x2, ....xn}. Firstly store the binary numbers from 1 to (2^n -1) in an array(in n digit format). Now traverse the array. While traversing a number, calculate the sum of product of i^th digit(of binary number) with i^th element. If it is equal to K the binary number, then print it. In this way obtain all the subsets whose sum equals K. This algorithm will work for negative numbers also. No issues about it. I hope this helps.

Shefali Bansal

I had asked the same question some time ago .Its a NP-Complete problem and cant be solved in O(N*k) , See this link for more details : (my question ws little different though, but approach is same ) Basically this can be solved in O(N*(abssum(allthe elements))

Ajit Kumar

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.