Array splitting I array-partition leetcode python

1. Topics

 

Given an array of length  2n  , your task is to divide these numbers into  n pairs, such as (a 1 , b 1 ), (a 2 , b 2 ), ..., (a n , b n ) such that from The sum of min(a i , b i ) from 1 to n is the largest.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n equals 2, the maximum sum is 4 = min(1, 2) + min(3, 4).

hint:

  1. n  is a positive integer in the range [1, 10000].

  2. Elements in the array are in the range [-10000, 10000].

2. Answer

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

 

The principle is this, to sort first, so that the small elements and the smallest combinations other than it do not sacrifice the large ones. In this way, the harmony will be the greatest. Here the sort method in python list is used to sort.

 

http://www.codeblogbt.com/archives/39689

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324950105&siteId=291194637