[LeetCode] 561. Array Partition I

Easy

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:

  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].

题目大意:有一个包含2n个整数的数组,将数组中的数字两两分组,求出这些组中的最小值相加之和的最大值。

为使最后加和最大,那么就要各组选出的最小值尽可能大,当每一组的两个数字相差都最小时,得出的最小值之和才会最大。

因此先对整个数组排序,然后从前往后依次两两组队,取出每组的最小值相加,就能得到最大的和。

因为数组已经排过序了,所以就能省去取组内最小值这一步。当数组是非降序排列时,数组的偶数位就是各组的最小值。

代码如下:

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        int res=0;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size()/2;++i){
            res+=nums[i*2];
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/cff2121/p/11446739.html