[LeetCode] Array Partition I 數組分割之一


 

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.

 

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) {
        int res = 0, n = nums.size();
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n; i += 2) {
            res += nums[i];
        }
        return res;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM