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
nelements belonging to the first part and their sum issumfirst. - The next
nelements belonging to the second part and their sum issumsecond.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code