Array Partition - Problem
You're given an array of 2n integers and need to form n pairs to maximize a specific sum. Here's the challenge: for each pair (a, b), you only get to keep the smaller value min(a, b) toward your total score.
Goal: Group the integers into pairs such that the sum of all minimum values is as large as possible.
Example: With array [1, 4, 3, 2], you could pair as (1,4) and (3,2), giving you min(1,4) + min(3,2) = 1 + 2 = 3. But there's a better way!
Input: An integer array nums of length 2n
Output: The maximum possible sum of minimum values from optimal pairing
Input & Output
example_1.py โ Basic Case
$
Input:
[1,4,3,2]
โบ
Output:
4
๐ก Note:
Sort to get [1,2,3,4]. Pair as (1,2) and (3,4). Sum of minimums: min(1,2) + min(3,4) = 1 + 3 = 4.
example_2.py โ All Same Values
$
Input:
[6,2,6,5,1,2]
โบ
Output:
9
๐ก Note:
Sort to get [1,2,2,5,6,6]. Pair as (1,2), (2,5), (6,6). Sum of minimums: 1 + 2 + 6 = 9.
example_3.py โ Minimum Case
$
Input:
[1,2]
โบ
Output:
1
๐ก Note:
Only one pair possible: (1,2). Sum of minimums: min(1,2) = 1.
Constraints
- 1 โค n โค 104
- nums.length == 2 * n
- -104 โค nums[i] โค 104
- Array length is always even
Visualization
Tap to expand
Understanding the Visualization
1
Line Up Players
Sort all players by skill level from weakest to strongest
2
Form Adjacent Teams
Pair consecutive players: weakest with 2nd weakest, 3rd with 4th, etc.
3
Calculate Tournament Strength
Sum up each team's strength (their weaker player's skill)
Key Takeaway
๐ฏ Key Insight: Sort first, then pair consecutive elements. This greedy approach minimizes 'waste' by ensuring each element is paired with the closest possible partner in value.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code