标签:input min xpl 长度 class tput 解决 其他 NPU
题目的大意为给定一个长度为2n的数组,把数组分为n对,使从1到n的min(ai,aj)的总和最大。
比如:
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).
拿到这道题,发现排序后比较好解决。
可以发现排序后相邻两个元素分组,把奇数位置的元素相加即为所求。
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int sum = 0;
for (int i = 0; i < nums.length; i += 2) {
sum += nums[i];
}
return sum;
}
也有其他更好的方法,正在探索当中。
LeetCode.561. Array Partition I
标签:input min xpl 长度 class tput 解决 其他 NPU
原文地址:https://www.cnblogs.com/xusong95/p/10226975.html