561. Array Partition I

来源:互联网 发布:161631人工智能怎么 编辑:程序博客网 时间:2024/05/16 06:31

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

Example 1:

Input: [1,4,3,2]Output: 4Explanation: n is 2, and the maximum sum of pairs is 4.

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. 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;    }};


0 0