题目大意:
给定一个长度为2n的数组,将它分为n个小组,每组两个元素。求出每组中最小值和,返回其中最大的和sum。
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].
解题思路:
- 先排序,将相邻两个数分为一组,每组较小数都在左边,求和即可
代码如下:
public class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int num = 0;
for(int i = 0;i < nums.length;i+=2){
num +=nums[i];
}
return num;
}
}