how to solve this problem:
We are given N pairs of integers. For each pair of integers, we have to assign one integer to A and the other to B, such that the difference between the sum of integers assigned to A and the sum of integers assigned to B is minimum.
I can’t think of anything better than O(2^N).
I thought of greedy but it doesn’t always give the optimal result.
how to solve this problem: We are given N pairs of integers. For each
Share
Transform the problem into this:
Given: a sequence of non-negative integers (the absolute difference between the original pairs)
Problem: Partition the integers into two sets so as to minimize the absolute difference of the sums of the elements of each subset.
This is the Balanced Partition Problem which is NP-complete. The two problems are equivalent; that is, you can transform the Balanced Partition Problem into your problem: associate, for each element ni of the sequence, the integer pair (ni, 0). Thus, you aren’t going to do better than O(2N).
Problem: assign a sign (plus/minus) to each integer such that the absolute value of the sum of the sequence is minimal.I suspect* that if you first sort the sequence in descending order, then a greedy algorithm will give optimal results. This will be an O(N log N) algorithm.
(*) If I’m wrong, please post a counter-example.