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 = min(1, 2) + min(3, 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].
題目大意: 給定一個長度為2n(偶數(shù))的數(shù)組,分成n個小組,返回每組中較小值的和sum,使sum盡量大
思路:
先排序,將相鄰兩個數(shù)分為一組,每組較小數(shù)都在左邊,求和即可算法分析: 查看英文版請點擊上方
假設(shè)對于每一對i,bi >= ai。 定義Sm = min(a1,b1)+ min(a2,b2)+ … + min(an,bn)。最大的Sm是這個問題的答案。由于bi >= ai,Sm = a1 + a2 + … + an。 定義Sa = a1 + b1 + a2 + b2 + … + an + bn。對于給定的輸入,Sa是常數(shù)。 定義di = | ai - bi |。由于bi >= ai,di = bi-ai, bi = ai+di。 定義Sd = d1 + d2 + … + dn。 所以Sa = a1 + (a1 + d1) + a2 + (a2 + d2) + … + an + (an + di) = 2Sm + Sd , 所以Sm =(Sa-Sd)/ 2。為得到最大Sm,給定Sa為常數(shù),需要使Sd盡可能小。 所以這個問題就是在數(shù)組中找到使di(ai和bi之間的距離)的和盡可能小的對。顯然,相鄰元素的這些距離之和是最小的。
code:

    func arrayPairSum(_ nums: [Int]) -> Int {
    var nums = nums.sorted(){$1 > $0}
    var result:Int = 0
    let length = nums.count
    var j = 0
    for i in  0 ..< nums.count{
        if j==0 {
            result += nums[i]
            j = 1
        }else{
            j = 0
        }
    }
    return result
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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