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: 4Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 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].
【题目】:对长度为2n的list进行随机分组,计算每个组最小值的和的最大值。此题不是考编程,考的是分析题目的能力,否则会去想怎么暴力地取数组对。分析之后可以知道,一个数只有和大于这个数的距离这个数最近的数进行取最小值,求和之后才能得到总的最大值;因此只用将list从小到大排序,从第一个开始每隔两个数进行取数求和。用python一行代码即可。
【解】
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])