Leetcode学习(3)—— Array Partition I

xiaoxiao2021-02-28  106

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.

给出一个长度为 2n 的整数数组,你的任务是将这些整数分成n组,每组两个一对,并求得 所有分组中较小的数 的总和(这个总和的值要尽可能的大)

Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4.

Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000].

思路:将整个数组升序排列,从下标为 0 处开始,每隔两个 取一个,并求和

class Solution(object): def arrayPartitionI(self, nums): return sum(sorted(nums)[::2])
转载请注明原文地址: https://www.6miu.com/read-42476.html

最新回复(0)