561.Array Partition I
這是leetCode第561題,難度Easy
題目
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.
意思是:給出一個2n個整數(shù)的數(shù)組例隆,你的任務(wù)是將這些整數(shù)分組為n對整數(shù)勇凭,如(a1,b1),(a2,b2),...(an,bn)從而在i為1到n的時候加勤,使(ai,bi)最小值的總和盡可能得大
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].
思路:
要把n組整數(shù)的最小值的和稠集,盡可能大凛澎。就意味著展氓,要盡可能的把大一些的值分在一組兔综,小一點的值分在一組燕刻,這樣得到n個最小值的時候只泼,大一點的數(shù)字就多,小一點的數(shù)字就小卵洗,結(jié)果就盡可能大请唱。
因此,我們需要對數(shù)組進行排序过蹂,從小到大排序十绑。從數(shù)組索引位置0開始,倆倆為一組酷勺。那么每組最小值的索引就是0本橙,2,4鸥印,...
代碼如下:
var arrayPairSum = function (nums) {
var l = nums.length;
var sum = 0;
//對數(shù)組進行排序勋功,從小到大排
nums.sort(function (a, b) {
if (a < b) {
return -1;
} else {
return 1;
}
});
for (var i = 0; i < l; i += 2) {
//每一組的最小值,索引都是偶數(shù)
sum += nums[i];
}
return sum;
};