Statement▼
You are given an integer array, nums, consisting of
Your task is to divide the array into two subarrays of length nums belongs to exactly one of the two subarrays, and the absolute difference between their sum is minimized.
Return the minimum possible absolute difference between the sum of the two subarrays.
Constraints:
1
≤ n ≤ 15nums.length==2∗n −107 ≤ nums[i]≤ 107
Solution
The essence of this solution lies in minimizing the absolute difference between the sums of two equal-sized subarrays by leveraging the binary search pattern combined with the meet-in-the-middle strategy. Instead of evaluating all possible partitions, which would be computationally infeasible due to the exponential number of subsets, the array is split into two halves. All possible subset sums are computed for each half, along with the number of elements used to form them. The key insight is that for each subset generated from the left half, we determine how many elements are needed from the right half (so the total subset size equals n), and then use binary search to efficiently find the best-matching subset from the right half whose sum brings the total closest to half the total array sum.
This process is both precise and optimized because:
Right-half subsets are pregrouped by their size, making it possible to only consider valid combinations (those with a total of
nelements).Each group of subset sums is sorted, allowing binary search to be used for fast and accurate retrieval of the closest matching subset sum.
Only 2ⁿ subsets are generated per half (not 2^(2n)), drastically reducing time complexity.
As a result, this method efficiently finds the best partition without exhaustively testing all combinations, achieving a powerful reduction in both time and space.
Now, let’s look at the solution steps below:
Compute
half_len,total_sum, andtarget_sumas the key parameters to guide the partitioning logic.Split
numsintoleft_halfandright_half.Generate all subset sums for
left_halfand store them as(count, subset_sum)pairs inleft_subsets.Generate all subset sums for
right_halfand store them inright_subsets.Group
right_subsetsinto a dictionaryright_sum_dictbycount, and sort each group for binary search.For each subset in
left_subsets, compute how many elements must come from the right (right_count = half_len - count).Use binary search on
right_sum_dict[right_count]to find the closest sum totarget_sum - left_sum.Track the smallest difference encountered and update
min_diffaccordingly.Return the final result as
min_diff * 2 + total_sum % 2.
Let’s look at the following illustration to get a better understanding of the solution: