[LeetCode] #561. Array Partition I
題目
Given an integer array nums of 2n
integers, group these integers into n
pairs (a1, b1), (a2, b2), ..., (an, bn)
such that the sum of min(ai, bi)
for all i
is maximized. Return the maximized sum.
直覺解
構想:
由小到大排序之後,兩兩一組取最小的數字相加,也就是,取 index 為偶數的數字相加。
python3 實作:
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
nums.sort()
return sum(nums[::2])
效能:
Runtime: 264 ms, faster than 62.64% of python3 online submissions for Array Partition I.
Memory Usage: 16.7 MB, less than 82.74% of python3 online submissions for Array Partition I.
Comments
Post a Comment