class Solution:
def arrayPairSum(self, nums):
nums.sort()
return sum(nums[::2])
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int sum = 0;
for (int i = 0; i < nums.size(); i += 2) {
sum += nums[i];
}
return sum;
}
};
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}
return sum;
}
}
var arrayPairSum = function(nums) {
nums.sort((a, b) => a - b);
let sum = 0;
for (let i = 0; i < nums.length; i += 2) {
sum += nums[i];
}
return sum;
};
Given an array nums
of 2n
integers, your task is to pair these integers into n
pairs such that the sum of the minimum value in each pair is maximized. In other words, you should:
n
pairs from 2n
elements, using each element exactly once (no reuse).Constraints:
nums
is an integer.nums.length
is always even.At first glance, it might seem that we need to try all possible ways to pair up the numbers and check which combination gives the highest sum of minimums. This brute-force approach would quickly become infeasible as the array grows, due to the sheer number of ways to pair elements.
To optimize, we need to observe a pattern or property that lets us find the answer without checking every possibility. By analyzing small examples, we can see that pairing the smallest numbers together and the next smallest together, and so on, gives the best result. This is because pairing a small number with a much larger number "wastes" the larger number (since only the minimum counts), whereas pairing similar numbers keeps more of the larger numbers available for other pairs.
Thus, sorting the array and taking every other element (starting from the smallest) for the sum is the optimal strategy.
Here’s how we solve the problem step by step:
nums
in ascending order.
We use sorting (which is efficient and easy to implement) and then a simple loop to compute the sum.
Let’s walk through an example with nums = [1, 4, 3, 2]
:
[1, 2, 3, 4]
1
and 2
(minimum is 1
)3
and 4
(minimum is 3
)1 + 3 = 4
4
.
If we tried any other pairing (for example, (1, 3)
and (2, 4)
), the sum of minimums would be 1 + 2 = 3
, which is less than 4
. This confirms that the sorted-pairing approach is optimal.
O((2n)! / (n! * 2^n))
. This is completely impractical for even moderate values of n
.O(n \log n)
time.O(n)
time.O(n \log n)
O(1)
extra space (if sorting in-place), or O(n)
if the language's sort creates a copy.
The key insight for solving the Array Partition problem is realizing that pairing numbers in sorted order (smallest with next smallest) maximizes the sum of the minimums. This avoids "wasting" large numbers by pairing them with much smaller ones. By sorting the array and summing every other element, we get an efficient and elegant solution with O(n \log n)
time complexity and minimal space usage. This approach is both intuitive and optimal for the problem constraints.