Problem: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数组,任意组合为n对(ai,bi),求Min(a,b)和,求出可能组合中使求和最大。
思路:本来一开始没太懂意思,但是研究题意找出了规律。
首先排序,再每两个相邻两个划分为一组,即(i,i+1),i-(1,3,5...),再求i为奇数位数的和。即为最后解的结果。
解完题仔细一想,题意中是找出最大和,如果每对中数都是最小的,大一点的在其余对中,才会有可能取值到,这样求和才比较大。
代码:
class Solution {
public int arrayPairSum(int[] nums) {
int ret = 0;
Arrays.sort(nums);
for(int i=0;i<nums.length;i+=2){
ret +=nums[i];
}
return ret;
}
}
看提交有点amazing!!!