Split Array Into Two Arrays to Minimize Sum Difference

Partition 2n integers into two n-sized halves minimizing |sumA − sumB| — meet-in-the-middle + binary search.

Hard
Time O(n * 2^n) Space O(n * 2^n)
LeetCode
9 min read
binary-search meet-in-the-middle bitmask

Problem#

Split nums (length 2n) into two arrays of length n each. Minimize |sumA - sumB|.

Examples#

  • nums = [3,9,7,3]2

Constraints#

  • 1 <= n <= 15.

Hints#

Hint 1
Split into halves. Each half contributes some subset to A. For each (size, sum) combo from the left half, look up the closest counterpart in the right half via binary search.

Approach#

Meet in the middle. For each half, enumerate all 2^n subsets and group sums by subset size. We want sumA = sumL_subset + sumR_subset where left and right contributions have sizes summing to n. The target sumA for minimum diff is total / 2. For each left subset of size k with sum sl, binary-search the right’s size-(n - k) bucket for the value closest to total/2 - sl.

Solution#

Split to Minimize Sum Difference
class Solution {
public:
int minimumDifference(vector<int>& nums) {
int n = nums.size() / 2;
long long total = accumulate(nums.begin(), nums.end(), 0LL);
vector<vector<long long>> L(n + 1), R(n + 1);
for (int mask = 0; mask < (1 << n); ++mask) {
long long sl = 0, sr = 0;
int cnt = __builtin_popcount(mask);
for (int i = 0; i < n; ++i) if (mask >> i & 1) {
sl += nums[i];
sr += nums[n + i];
}
L[cnt].push_back(sl);
R[cnt].push_back(sr);
}
for (auto& v : R) sort(v.begin(), v.end());
long long best = LLONG_MAX;
for (int k = 0; k <= n; ++k) {
const auto& cand = R[n - k];
if (cand.empty()) continue;
for (long long sl : L[k]) {
long long need = total - 2 * sl; // want 2 * sr ≈ need
long long needHalf = need / 2;
auto it = lower_bound(cand.begin(), cand.end(), needHalf);
for (auto p : {it, (it == cand.begin() ? cand.end() : prev(it))}) {
if (p == cand.end()) continue;
long long sumA = sl + *p;
best = min(best, llabs(total - 2 * sumA));
}
}
}
return (int)best;
}
};

Editorial#

Brute force is C(2n, n) partitions — for n=15, ~155 million. Meet-in-the-middle enumerates 2^15 = 32k subsets per half. The “size index” constraint enforces that the two halves combine to a size-n partition; sorting each right-bucket and binary-searching is O(log 2^n) = O(n) per left subset.

Complexity#

  • Time: O(n * 2^n).
  • Space: O(n * 2^n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.