Description:
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Note:
- n is a positive integer, which is in the range of [1, 10000].
- All the integers in the array will be in the range of [-10000, 10000].
思路:本题要求对数组中的元素两两分组,取每组的最小值,最后把每组最小值相加,求如何组合得到最大的和。细想本题,我们只需使每个组的两个元素相差尽量小,以免浪费较大的数字。先对数组排序,从第一个元素开始,隔一个元素取一个数字,再相加即可。
C++ 代码
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int ret =0;
sort(nums.begin(), nums.end());
for (int i=0; i<nums.size(); i = i+2){
ret += nums[i];
}
return ret;
}
};
运行时间:92ms
运行内存:11.4M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于