Problem Description
Given an integer array nums of length 2*n, partition the array into two arrays each of length n such that the absolute difference between their sums is minimized. You achieve this by choosing exactly n elements for one array, with the remaining forming the other array. Return the minimum possible absolute difference between the sums of the two arrays.
Key Insights
- The problem is equivalent to choosing n elements from 2*n such that the sum of chosen elements is as close as possible to half of the total sum.
- Use the meet-in-the-middle strategy by splitting the array into two halves; each half has at most 15 elements.
- For each half, enumerate all possible subset sums along with the count of elements chosen.
- Combine subset sums from the first and second halves with complementary counts (j and n-j) and use binary search to quickly find the best pairing that minimizes the absolute difference.
- The final answer is given by abs(total - 2*(chosenSubsetSum)).
Space and Time Complexity
Time Complexity: O(2^(n) * n) due to enumerating subset sums in each half (with n up to 15, 2^(15) is feasible) and then combining results with binary search. Space Complexity: O(2^(n)) for storing subset sums for each half.
Solution
We use a meet-in-the-middle approach:
- Divide the array into two halves.
- For each half, generate all possible subset sums along with the number of elements selected. This can be stored in a dictionary keyed by the count of selected numbers.
- The goal is to form a subset of exactly n elements. For every possible selection count j from the first half, pair it with selections of n-j from the second half.
- For each pair, compute the total subset sum. The optimal subset sum should be as close as possible to half the total sum. Thus, the minimum absolute difference is given by abs(total - 2*(subset sum)).
- To efficiently find the best sum candidate from the second half for a given value from the first half, sort the sums from the second half for each selection count and use binary search.
- Return the minimal absolute difference found.