Note that there are some explanatory texts on larger screens.

plurals
  1. POInstance of subset sum problem
    primarykey
    data
    text
    <p>I have a problem which is a pretty clear instance of the subset sum problem:</p> <p>"given a list of Integers in the range [-65000,65000], the function returns true if any subset of the list summed is equal to zero. False otherwise."</p> <p>What I wanted to ask is more of an explanation than a solution.</p> <p>This was an instance-specific solution I came up before thinking about the complexity of the problem.</p> <ul> <li>Sort the array A[] and, during sort, sum each element to a counter 'extSum' (O(NLogN))</li> <li>Define to pointers low = A[0] and high = A[n-1]</li> <li>Here is the deciding code:</li> <li><pre><code>while(A[low]&lt;0){ sum = extSum; if(extSum&gt;0){ while(sum - A[high] &lt; sum){ tmp = sum - A[high]; if(tmp==0) return true; else if(tmp &gt; 0){ sum = tmp; high--; } else{ high--; } } extSum -= A[low]; low++; high = n - 1; } else{ /* Symmetric code: switch low, high and the operation &gt; and &lt; */ } } return false; </code></pre></li> </ul> <p>First of all, is this solution correct? I made some tests, but I am not sure...it looks too easy...<br> Isn't the time complexity of this code O(n^2)?</p> <p>I already read the various DP solutions and the thing I would like to understand is, for the specific instance of the problem I am facing, how much better than this naive and intuitive solution they are. I know my approach can be improved a lot but nothing that would make a big difference when it comes to the time complexity....</p> <p>Thank you for the clarifications</p> <p><strong>EDIT:</strong> One obvious optimization would be that, while sorting, if a 0 is found, the function returns true immediately....but it's only for the specific case in which there are 0s in the array.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload