Skip to main content
Back to problems
Leetcode
Medium
Arrays
Heaps
Dynamic Programming
Amazon
Minimum Difference in Sums After Removal of Elements

Choose nn elements to remove from the middle of a 3n3n-length array so that the difference between the sum of the left kept part and the right kept part is minimized.

Acceptance 100%
Problem Statement

You are given an integer array of length 3n3n. You must remove exactly nn elements from the array, and the remaining 2n2n elements must be split into two parts of length nn each:

  • the first nn kept elements from the left side,
  • the last nn 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:

sum(left kept n elements)sum(right kept n elements)\text{sum(left kept n elements)} - \text{sum(right kept n elements)}

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 nums of length 3n.
  • It is guaranteed that the length of nums is 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 nn elements.

Constraints

  • 1n1 \le n
  • nums=3n|nums| = 3n
  • Element values may be positive, negative, or zero.
  • Solve using a method that is efficient for large arrays.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [3, 1, 2]

Output

1

Explanation

Here n=1n=1. 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 n=2n=2. 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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.