Choose elements to remove from the middle of a -length array so that the difference between the sum of the left kept part and the right kept part is minimized.
You are given an integer array of length . You must remove exactly elements from the array, and the remaining elements must be split into two parts of length each:
- the first kept elements from the left side,
- the last kept elements from the right side.
Your goal is to minimize the difference between the sum of the left kept part and the sum of the right kept part.
Return the minimum possible value of:
The removed elements can come from anywhere, but the kept left part must be chosen from a prefix and the kept right part must be chosen from a suffix in the natural order of the array.
Input Format
- An integer array
numsof length3n. - It is guaranteed that the length of
numsis divisible by 3.
Output Format
- Return the minimum possible value of the difference between the sum of the left kept part and the sum of the right kept part after removing exactly elements.
Constraints
- Element values may be positive, negative, or zero.
- Solve using a method that is efficient for large arrays.
Example 1
Input
nums = [3, 1, 2]
Output
1
Explanation
Here . Remove the middle element 1, keep 3 on the left and 2 on the right. The difference is 3 - 2 = 1, which is minimal.
Example 2
Input
nums = [7, 9, 5, 8, 1, 3]
Output
1
Explanation
Here . One optimal choice is to keep left sum 7 + 5 = 12 and right sum 8 + 3 = 11, giving difference 1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.