1. 程式人生 > >【python3】leetcode 561. Array Partition I (easy)

【python3】leetcode 561. Array Partition I (easy)

561. Array Partition I (easy)

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).

這道題提意不清,其實是要求把一個2n的array兩兩一組,將每組的最小值相加,問如何得到的和最大,

即sum(all min(xi,xj)) 

萬能排序,然後按2個一組,min就是下標為偶數的數

class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return sum([nums[i] for i in range(len(nums)) if i%2==0 ])

Runtime: 124 ms, faster than 62.36% of Python3