#2035

Partition Array Into Two Arrays to Minimize Sum Difference

Hard
ArrayTwo PointersBinary SearchDynamic ProgrammingBit ManipulationSortingOrdered SetBitmaskDynamic ProgrammingSubset Sum Problem
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^n * n)
O(n * target)
Space
O(1)
O(target)
💡

Intuition

Time O(n * target)Space O(target)

The optimal solution uses dynamic programming to explore possible sums that can be achieved with half of the elements. It focuses on finding the closest sum to half of the total sum, which minimizes the difference between the two partitions.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total sum of the array and determine the target sum as total_sum / 2.
  2. 2Step 2: Use a dynamic programming array to track achievable sums with n elements from the array.
  3. 3Step 3: Iterate through the nums array and update the DP array for possible sums.
  4. 4Step 4: Find the maximum achievable sum that is less than or equal to the target sum, and calculate the minimum difference.
solution.py12 lines
1def minAbsDifference(nums):
2    n = len(nums) // 2
3    total_sum = sum(nums)
4    target = total_sum // 2
5    dp = [False] * (target + 1)
6    dp[0] = True
7    for num in nums:
8        for j in range(target, num - 1, -1):
9            dp[j] = dp[j] or dp[j - num]
10    for i in range(target, -1, -1):
11        if dp[i]:
12            return abs(total_sum - 2 * i)

Complexity note: The time complexity is O(n * target) where n is the number of elements and target is half of the total sum. The space complexity is O(target) for the DP array.

  • 1The problem can be viewed as a variation of the subset-sum problem.
  • 2Finding a partition that minimizes the difference between sums is akin to balancing weights on a scale.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.