leetcode-561-Array Partition I

Topic 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:

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

 

Function to be done:

int arrayPairSum(vector<int>& nums) 

 

illustrate:

1. Given a vector, which contains 2n elements, these elements should be formed into n pairs, such as [1,3,2,4], which can be formed into pairs such as [1,2], [3,4] son.

Find the minimum value of each pair, and then add the minimum values ​​to sum up. To maximize the sum, how should the pairs be formed? What is the largest sum that can be output?

 

2. Let's think about it, for example, for a vector such as [1,3,2,4], whether the maximum value of 4 can be used as part of the sum, obviously not, no matter who 4 is matched with, it cannot be output.

What about 3, the second largest number? 3 can only be output when it is together with 4.

What about 2? If 2 is matched with 4, and 3 is matched with 1, then 2 can be output, but 3 cannot be output. Losing a 3 for a 2 is obviously not worth it.

So the most ideal match is [3,4] output 3, [1,2] output 1, we want to make the largest number as much as possible to reflect its value.

 

3. The idea is very clear, the code is as follows:

    int arrayPairSum(vector<int>& nums) 
    {
        sort(nums.begin(),nums.end());//Ascending order
        int s1=nums.size(),sum=0;
        for(int i=0;i<s1;i+=2)
            sum+=nums[i];
        return sum;
    }

The code is concise, measured 76ms, beats 78.50% of cpp submissions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325229214&siteId=291194637