My rules:
- Duplicates are allowed
- negative numbers are allowed obviously
- Since i mentioned partition, it means you cannot put an element from the array in more than 1 partition
- Elements in partition are subsets/need not be contiguous chunks of array
- elements in input array are not in sorted order
- Sum of all the elements in input array will aways be 0(given condition)
Example: if A = {-2,-4,-6,+6,+6} then B={{-2,-4,6},{+6,-6}} is the result with the max no of partitions
FYI, I want to return all the partitions and not the number of partitions.
From my research, this seemed like a NP-hard/complete problem. But I'm not sure about it and would really appreciate if someone could explain the best way to go about it(even if its slow). Some psuedo-code would be appreciated too.
Thank you.
I agree that the problem is NP. Optimizing this is ugly, with a capital "ugh". You can improve the search time somewhat, but I fear that it's still O(2^N) and worse.
Now comes the ugly parts. The "relative" brute-force approach is to generate the power set of each partition; index by sum. For instance, given the list
2, 3, 4, 7:Now find all matches of abs(sum(subset)) between the positive and negative listings. These form the choices for your solution space. My best recommendation from this point is to apply the
set coverage problemto this; you'll have to tweak slightly for duplicate values.