Array Partition - Problem

Given an integer array nums of 2n integers, group these integers into n pairs (a₁, b₁), (a₂, b₂), ..., (aₙ, bₙ) such that the sum of min(aᵢ, bᵢ) for all i is maximized.

Return the maximized sum.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,3,2]
Output: 4
💡 Note: After sorting: [1,2,3,4]. Pairs: (1,2) and (3,4). Sum of minimums: min(1,2) + min(3,4) = 1 + 3 = 4
Example 2 — Larger Array
$ Input: nums = [6,2,6,5,1,2]
Output: 9
💡 Note: After sorting: [1,2,2,5,6,6]. Pairs: (1,2), (2,5), (6,6). Sum of minimums: 1 + 2 + 6 = 9
Example 3 — Minimum Size
$ Input: nums = [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

Visualization

Tap to expand
Array Partition - Optimal Solution INPUT nums = [1, 4, 3, 2] 1 4 3 2 [0] [1] [2] [3] n = 2 (2n = 4 elements) Goal: Form n pairs Maximize sum of min(a,b) Pair 1: (a1,b1) Pair 2: (a2,b2) Find: min(a1,b1)+min(a2,b2) Maximized! ALGORITHM STEPS 1 Sort Array [1,4,3,2] --> [1,2,3,4] 1 2 3 4 2 Pair Adjacent Elements (1,2) and (3,4) (1, 2) (3, 4) 3 Take Min of Each Pair min(1,2)=1, min(3,4)=3 1 + 3 4 Sum Minimums 1 + 3 = 4 4 FINAL RESULT Optimal Pairing Found: Pair 1 (1, 2) Pair 2 (3, 4) Calculation: min(1,2) = 1 min(3,4) = 3 Sum = 1 + 3 = 4 OUTPUT 4 OK - Maximum Sum Achieved! Key Insight: Sorting ensures adjacent pairs have minimum difference. The smaller element of each pair contributes to the sum. By pairing sorted[0] with sorted[1], sorted[2] with sorted[3], etc., we maximize the sum of minimums. Time: O(n log n) for sorting. Space: O(1) if sorting in-place. TutorialsPoint - Array Partition | Optimal Solution
Asked in
Amazon 25 Microsoft 18 Facebook 15 Google 12
125.0K Views
Medium Frequency
~10 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