Minimum Difference in Sums After Removal of Elements - Problem

You are given a 0-indexed integer array nums consisting of 3 * n elements.

You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:

  • The first n elements belonging to the first part and their sum is sumfirst.
  • The next n elements belonging to the second part and their sum is sumsecond.

The difference in sums of the two parts is denoted as sumfirst - sumsecond.

For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.

Return the minimum difference possible between the sums of the two parts after the removal of n elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,4,2,5,6]
Output: -1
💡 Note: Remove [4,2,3] to get [1,5,6]. First part: [1], Second part: [5,6]. Difference: 1 - (5+6) = -10. This is one possible arrangement; optimal gives -1.
Example 2 — All Same Values
$ Input: nums = [7,7,7,7,7,7]
Output: 0
💡 Note: All elements equal, so any removal gives same sums for both parts. Difference is always 0.
Example 3 — Small Array
$ Input: nums = [20,40,20,70,30,50]
Output: -30
💡 Note: Remove [70,40,50] to get [20,20,30]. First: [20], Second: [20,30]. Difference: 20-50 = -30.

Constraints

  • nums.length == 3 * n
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Difference Problem: nums = [3,1,4,2,5,6]Step 1: Original Array (3n = 6 elements)314256Step 2: Remove n=2 elements [3,4] optimally1256First PartSecond PartStep 3: Calculate DifferenceSum First = 1Sum Second = 2 + 5 + 6 = 13Difference = 1 - 13 = -12
Understanding the Visualization
1
Input Array
Start with 3n elements that need to be processed
2
Remove n Elements
Strategically remove n elements to optimize the remaining parts
3
Calculate Difference
Divide remaining 2n elements and find sumfirst - sumsecond
Key Takeaway
🎯 Key Insight: To minimize difference, make first part sum as small as possible and second part sum as large as possible by strategically removing middle elements
Asked in
Google 15 Amazon 8 Microsoft 6
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen