Given an integer array nums of 2n integers, 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 maximized sum.
Input: nums =[1,4,3,2]Output: 4Explanation: All possible pairings(ignoring the ordering of elements) are:1.(1,4),(2,3)-> min(1,4)+ min(2,3)=1+2=32.(1,3),(2,4)-> min(1,3)+ min(2,4)=1+2=33.(1,2),(3,4)-> min(1,2)+ min(3,4)=1+3=4So the maximum possible sum is4.
To maximize the sum of the minimums of pairs, we should pair the smallest numbers together. By sorting the array and pairing every two consecutive elements, we ensure that each pair’s minimum is as large as possible, maximizing the total sum.
classSolution {
public:int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans =0;
for (int i =0; i < nums.size(); i +=2) {
ans += nums[i];
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintarrayPairSum(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for (int i = 0; i < nums.length; i += 2) {
ans += nums[i];
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
defarrayPairSum(self, nums: list[int]) -> int:
nums.sort()
ans: int =0for i in range(0, len(nums), 2):
ans += nums[i]
return ans