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ù)都在左邊吹泡,求和即可算法分析: 查看英文版請點(diǎn)擊上方
假設(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
}