LeetCode 2035. Partition Array Into Two Arrays to Minimize Sum Difference Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
2035. Partition Array Into Two Arrays to Minimize Sum Difference

Description

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:

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:

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 <= 15
  • nums.length == 2 * n
  • -107 <= nums[i] <= 107

Solutions

Solution 1

PythonJavaC++Go
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !