算法練習每日一題:數組拆分 I

561. 數組拆分 I

給定長度爲 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).

提示:

n 是正整數,範圍在 [1, 10000].
數組中的元素範圍在 [-10000, 10000].

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/array-partition-i

"""
# Testcase:
>>> Solution().arrayPairSum([1,4,3,2])
4

"""

class Solution:
    def arrayPairSum(self, nums):
        nums = sorted(nums, reverse=False)
        max_sum = 0
        n = len(nums)
        while n//2 :
            max_sum += min((nums[n-1],nums[n-2]))
            n -= 2
        return max_sum
    
if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)
Trying:
    Solution().arrayPairSum([1,4,3,2])
Expecting:
    4
ok
2 items had no tests:
    __main__.Solution
    __main__.Solution.arrayPairSum
1 items passed all tests:
   1 tests in __main__
1 tests in 3 items.
1 passed and 0 failed.
Test passed.

題解:

直觀模擬求解:將數組排序後,將最大與最小組合,等價於從右往左組合,保留最小值;
LeetCode上有數學推導,可以參考。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章