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.

Example1:

1
2
3
4
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.

Note:

1
2
1. n is a positive integer, which is in the range of [1, 10000].
2. All the integers in the array will be in the range of [-10000, 10000].

分析


思考这种问题有几个方向,一个是多举几个例子,从中找出规律,然后写代码解决即可,另一种是直接用抽象思维解决,还有一种就是比较学院派,用数学证明。这里解释一下我的思考。先考虑极端的情况,如果配对的方式是最小的值和最大的值配对,倒数第 2 小和倒数第 2 大的值配置… 想象这些值从左至右从小到大排序,那么我们拿到的就是左边那一半的数字的和,我们得到的结果就是所能获得的总数的最小值,题目要求是总数最大,那么选择的这些数字应该尽可能地向右边靠拢,最理想的情况就是相邻的数字进行比较,总数是第 2 大,第 4 大,第 6 大… 的值进行相加。所以说解决方案就是,先将数组进行排序,取第 0 个,第 2 个,第 4 个…直到第 2n-1 个即可。

讨论里有一个数学证明:https://discuss.leetcode.com/topic/87206/java-solution-sorting-and-rough-proof-of-algorithm/2

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
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;
}
}

解决方案2(Python)


1
2
3
4
5
6
7
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])

解决方案3(Golang)


1
2
3
4
5
6
7
8
func arrayPairSum(nums []int) int {
sort.IntSlice(nums).Sort()
var result int
for i := 0; i < len(nums); i += 2 {
result += nums[i]
}
return result
}

相关问题


题目来源