Array partition

Array partition

Difficulty of array division: Pass rate: 74% Number of submissions: 134 Subject source: Subject description Submission record description

Given an array of 2n integers, your task is to divide these integers into n groups, such as (a1, b1), (a2, b2),..., (an, bn). And make the sum of min(ai, bi) from 1 to n as large as possible.

n is a positive integer and the range is [1, 10000].
The range of the elements in the array is [-10000, 10000].
Example

Example 1:

Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the largest number pair sum is 4 = min(1, 2) + min(3, 4).
Example 2:

Input: [5,6]
Output: 5
Explanation: n is 1, and the largest sum of numbers is 5 = min(5, 6). This
problem was done for ten minutes, haha

It is sorted first, and then grouped in pairs according to 1, 3, 5...

class Solution {
    
    
public:
    /**
     * @param nums: an array
     * @return: the sum of min(ai, bi) for all i from 1 to n
     */
    int arrayPairSum(vector<int> &nums) {
    
    
        // Write your code here
   sort(nums.begin(), nums.end());
        int r = 0;
        for(int i = 0; i < nums.size(); i = i + 2)
        {
    
    
            r +=  nums[i];
        }
        return r;
    }

};

Posted on October 24, 2020Tag
algorithm
in Alibaba Cloud activity algorithm: Array partition

Guess you like

Origin blog.csdn.net/qq_44909275/article/details/109266641