Partition Array Into Two Arrays to Minimize Sum Difference Problem
Description
LeetCode Problem 2035.
You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:

Input: nums = [3,9,7,3]
Output: 2
Explanation: One optimal partition is: [3,9] and [7,3].
The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36]
Output: 72
Explanation: One optimal partition is: [-36] and [36].
The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:

Input: nums = [2,-1,0,4,-2,-9]
Output: 0
Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15nums.length == 2 * n-10^7 <= nums[i] <= 10^7
Solution
Approach: Meet in the middle
Splitting 2n numbers (n <= 15) into two groups of n numbers has up to C(30, 15) possibilities, which is too many to try one by one. Instead, cut the array into a left half and a right half of n numbers each and handle them separately.
In each half, enumerate the 2^n ways to choose some of its numbers for the first array. For each way, record the signed sum (chosen numbers count +, the others count -), grouped by the number of chosen numbers. If the left half chooses i numbers, the right half must choose n - i, so the two arrays end up with n numbers each.
The difference of the two final sums is the sum of the left signed sum and the right signed sum, so for each i we want a left value a and a right value b with |a + b| as small as possible. Sort the right values and, for every a, binary search the closest value to -a.
The time complexity is O(2^n * n) and the space complexity is O(2^n).
from collections import defaultdict
inf = float("inf")
class Solution:
def minimumDifference(self, nums: List[int]) -> int:
n = len(nums) >> 1
f = defaultdict(set)
g = defaultdict(set)
for i in range(1 << n):
s = cnt = 0
s1 = cnt1 = 0
for j in range(n):
if (i & (1 << j)) != 0:
s += nums[j]
cnt += 1
s1 += nums[n + j]
cnt1 += 1
else:
s -= nums[j]
s1 -= nums[n + j]
f[cnt].add(s)
g[cnt1].add(s1)
ans = inf
for i in range(n + 1):
fi, gi = sorted(list(f[i])), sorted(list(g[n - i]))
# min(abs(f[i] + g[n - i]))
for a in fi:
left, right = 0, len(gi) - 1
b = -a
while left < right:
mid = (left + right) >> 1
if gi[mid] >= b:
right = mid
else:
left = mid + 1
ans = min(ans, abs(a + gi[left]))
if left > 0:
ans = min(ans, abs(a + gi[left - 1]))
return ans