數組拆分 I array-partition leetcode python

來源:互聯網
上載者:User

標籤:python

1. 題目

 

給定長度為 2n 的數組, 你的任務是將這些數分成 n 對, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得從1 到 n 的 min(ai, bi) 總和最大。

樣本 1:

輸入: [1,4,3,2]輸出: 4解釋: n 等於 2, 最大總和為 4 = min(1, 2) + min(3, 4).

提示:

  1. n 是正整數,範圍在 [1, 10000].

  2. 數組中的元素範圍在 [-10000, 10000].

2. 解答
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

 

原理是這樣的,要先排序,這樣小的元素和除了它外最小的組合才不會犧牲大的。這樣和才會最大。這裡用了python list中的sort方法來進行排序。

 

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

數組拆分 I array-partition leetcode python

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.