This problem is loosely inspired by the topic of order statistics.
Partition problem: Given a set S of n distinct positive integers, determine if there exists a partition of the set into two parts A and B in such a way that the sum of the numbers in A equals the sum of the numbers in B.
Definition: The sets A and B form a partition of S if S = A ∪ B and ∅ = A ∩ B.
An algorithm for the problem:
bool partition(Ptr b, Ptr e)
/* [b..e) references a range of positive integers.
* Return true iff a partition of the values in range [b..e) exists
* solving the partition problem.
*/
{ integer S = 0;
for(Ptr i = b; i < e; ++i) S += *i;
if (S is odd) return false;
else return SubsetSum(b, e, S/2);
}
bool SubsetSum(Ptr b, Ptr e, integer T)
/* [b..e) references a range of positive integers.
* T is a nonnegative integer.
* Return true iff a subset from the range [b..e) exists whose sum is exactly T.
*/
{ size_t n = e - b;
if (n == 0) return T == 0;
if (T < *b) return SubsetSum(b+1, e, T); // *b can't be used.
// else solution not using *b or solution using *b to be checked.
return SubsetSum(b+1, e, T)
|| SubsetSum(b+1, e, T - *b);
}
Correction Oct 9: recursive calls not to "targettedSubsetSum"
Exercise:
Hint: Consider the data set 2, 4, ..., 2n.