【LeetCode-Algorithms】561. 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:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].

題目大意:

給定一個(gè)2n個(gè)整數(shù)的數(shù)組,你的任務(wù)是將這些整數(shù)分成n對(duì)整數(shù),例如(a 1,b 1),(a 2,b 2),...,(a n,b n)所有i從1到n 的最?。╝ i,b i)的和盡可能大。

示例1:
輸入: [1,4,3,2]
輸出: 4
說(shuō)明: n為2,最大對(duì)數(shù)為4。

注意:
n是正整數(shù),在[1,10000]的范圍內(nèi)。
數(shù)組中的所有整數(shù)將在[-10000,10000]的范圍內(nèi)。

解題思路

題目大意為要將2n個(gè)數(shù)最終形成n個(gè)數(shù)對(duì),每個(gè)數(shù)對(duì)中最小元素的和最大。
即取數(shù)對(duì)中較小的元素,并且要求和最大。
所以要求數(shù)對(duì)的元素之間的差值盡可能小,這樣選取小數(shù)據(jù)時(shí),損失不會(huì)太大。
所以只需將數(shù)組進(jìn)行排序,排序后將對(duì)較小的元素進(jìn)行求和就好了

具體實(shí)現(xiàn)

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int min = 0;
        for(int i=0; i < nums.size(); i=i+2)
        {
            min += nums[i];
        }
        return min;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容