版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/85045415
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 = min(1, 2) + min(3, 4).
这道题提意不清,其实是要求把一个2n的array两两一组,将每组的最小值相加,问如何得到的和最大,
即sum(all min(xi,xj))
万能排序,然后按2个一组,min就是下标为偶数的数
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return sum([nums[i] for i in range(len(nums)) if i%2==0 ])
Runtime: 124 ms, faster than 62.36% of Python3