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
Basketball Team Formation AnalogyAvailable Players (Skills): [1, 4, 3, 2]1432Step 1: Sort by Skill Level1234Step 2: Form Teams (Adjacent Pairs)12Team AStrength: 134Team BStrength: 3Step 3: Calculate Total Tournament StrengthTeam A Strength + Team B Strength = 1 + 3 = 4Maximum Tournament Strength: 4Why This Strategy WorksโŒ Bad Strategy: Pair 1 with 4โ€ข Team strength = min(1,4) = 1โ€ข "Wastes" player 4's high skillโœ… Good Strategy: Pair 1 with 2โ€ข Team strength = min(1,2) = 1โ€ข Only "wastes" 1 skill pointโ€ข Leaves stronger players for other team๐Ÿ’ก Minimize waste by pairing similar skills!
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.
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 6
89.4K Views
Medium Frequency
~15 min Avg. Time
2.8K 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