Description: Given an array of integers, partition the array into two subsets such that the absolute difference of their sums is minimized. Return the minimal absolute sum.
Example 1:
Input: numbers = [1, 5, 2, -2] Output: 0
Example 2:
Input: numbers = [3, 1, 4, 2, 2] Output: 0
Example 3:
Input: numbers = [1, 2, 3, 9] Output: 3
Algorithmic Steps This problem is solved using dynamic programming (subset sum):
- Calculate the total sum of the array.
- Use a boolean DP array to track possible subset sums up to half the total sum.
- For each number, update the DP array for all possible sums.
- Find the largest subset sum not exceeding half the total sum.
- The minimal absolute sum is the difference between the total sum and twice this subset sum.
Time and Space complexity:
- Time complexity:
O(n * S), wherenis the number of elements andSis half the total sum. - Space complexity:
O(S).