[LeetCode]#561. Array Partition I
1 min readMay 12, 2020
Environment: Python 3.7
Key technique: slice
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).
Analysis:
- Sort it.
- Use slice nums[::2] and output is [1,3]
- Sum it and answer is 4.
Solution:
class Solution:
def arrayPairSum(self, nums):
nums.sort()
return sum(nums[::2])
Submissions:
Reference:
https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/369234/