561. 数组拆分 I
给定长度为 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].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/array-partition-i
"""
# Testcase:
>>> Solution().arrayPairSum([1,4,3,2])
4
"""
class Solution:
def arrayPairSum(self, nums):
nums = sorted(nums, reverse=False)
max_sum = 0
n = len(nums)
while n//2 :
max_sum += min((nums[n-1],nums[n-2]))
n -= 2
return max_sum
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
Trying:
Solution().arrayPairSum([1,4,3,2])
Expecting:
4
ok
2 items had no tests:
__main__.Solution
__main__.Solution.arrayPairSum
1 items passed all tests:
1 tests in __main__
1 tests in 3 items.
1 passed and 0 failed.
Test passed.
题解:
直观模拟求解:将数组排序后,将最大与最小组合,等价于从右往左组合,保留最小值;
LeetCode上有数学推导,可以参考。