给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
示例 1:
输入: [1,4,3,2]
输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
提示:
n 是正整数,范围在 [1, 10000].
数组中的元素范围在 [-10000, 10000].
通过次数39,388提交次数55,351
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/array-partition-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
要使总和最大,则必须值最靠近的数字两两配对,因此对于列表排序后取两两配对的较小值求和
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=sorted(nums)
return sum([i for i in nums[::2]])
执行结果:
通过
显示详情
执行用时:292 ms, 在所有 Python 提交中击败了62.57%的用户
内存消耗:15 MB, 在所有 Python 提交中击败了33.33%的用户