【leetcode】561. Array Partition I

原题:

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.

解析:

数组分割1

给一组2n个整数,分割为n组,一组2个数,使min(a,b)之和最大

Example:

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 class ArrayPartitionI {
public static int arrayPartitionI(int[] array) {
Arrays.sort(array);
int sum = 0;
for (int i = 0; i < array.length - 1; i += 2) {
sum += array[i];
}
return sum;
}
}

最优解法

public class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int result = 0;
for (int i = 0; i < nums.length; i += 2) {
result += nums[i];
}
return result;
}
}

哈哈几乎一样,后来想了一下不用length-1也可以的

上一篇:[LeetCode] Array Partition I 数组分割之一


下一篇:[ASP.NET MVC2 系列] ASP.Net MVC教程之《在15分钟内用ASP.Net MVC创建一个电影数据库应用程序》