561. Array Partition I

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.

最优解应该是排序后,按顺序两两组成pairs,然后取所有pairs的第一个数的和。

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 0
        nums = sorted(nums)
        for i in range(0, len(nums), 2):
            ans += nums[i]
        return ans

 

posted @ 2020-06-29 14:13  whatyouthink  阅读(66)  评论(0编辑  收藏  举报