您的位置:首页 > 其它

561. Array Partition I

2017-05-02 20:35 381 查看
题目:给定一个序列有2n个数,目标是把它们分成n组,(ai,bi),使得ai和bi中较小的那个的所有的加和最大,输出这个值。

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 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].

思路:排序,将奇数位的数相加
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
int n=nums.size();
if(n%2) return 0;
int sum=0;
for(int i=0;i<n;i++)
{
sum+=nums[i];
i++;

}
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 数组