53-最大自序和

题目:

53-最大自序和_第1张图片

 

解答

53-最大自序和_第2张图片

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

 

 

解法二:

53-最大自序和_第3张图片

class Solution2:
    def maxSubArray(self, A):
        if not A:
            return 0
        curSum = maxSum = A[0]
        for num in A[1:]:
            curSum = max(num, curSum + num)
            maxSum = max(maxSum, curSum)

        return maxSum

 

你可能感兴趣的:(基础算法)