LeetCode 53 Maximum Subarray (Python)

Posted by 小明MaxMing on April 26, 2020

题目

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

解题思路

贪心,到当前位置并且包括当前数字的最大子数组,可以是这个数自己,或者自己加上之前上到上一个数的最大子数组

cur = max(nums[i], cur + nums[i])

代码

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        res = cur = nums[0]
        for n in nums[1:]:
            cur = max(cur + n, n)
            res = max(res, cur)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅