Given an integer array nums
of 2n integers, your task is to group these integers into n pairs (a1, b1), (a2, b2), …, (an, bn) such that the sum of min(ai, bi)
for all i is maximized. Return the maximum sum.
nums
?
n
is always guaranteed to be a positive integer such that the length of nums
is 2n
.The key insight here is to recognize that to maximize the sum of min(ai, bi)
, we should try to make pairs with the smallest difference between ai
and bi
. Sorting the array will help us achieve this.
Suppose nums = [1, 4, 3, 2]
.
#include <vector>
#include <algorithm>
class Solution {
public:
int arrayPairSum(std::vector<int>& nums) {
// Sort the array
std::sort(nums.begin(), nums.end());
int max_sum = 0;
// Sum up the elements at even indices
for (size_t i = 0; i < nums.size(); i += 2) {
max_sum += nums[i];
}
return max_sum;
}
};
This solution sorts the input array and then iterates through it to calculate the sum of the minimums of each pair, which efficiently maximizes the sum according to the problem’s requirement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?