Leetcode刷题记录——剑指 Offer 42. 连续子数组的最大和

Leetcode刷题记录——剑指 Offer 42. 连续子数组的最大和_第1张图片
前缀和算法

遍历一遍

pre = 0
max_res = nums[0] - 1
min_pre = 0
遍历到i位置时
pre+=nums[i]
max_res = max(max_res,pre-min_pre)
min_pre = min(min_pre,pre)

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if nums == []:
            return 0
        elif len(nums) == 1:
            return nums[0]
        max_sum = nums[0] - 1
        min_pre = 0 
        pre = 0
        index = 0
        length = len(nums)
        while index < length:
            pre += nums[index]
            max_sum = max(max_sum,pre-min_pre)
            min_pre = min(min_pre,pre)
            index += 1
        return max_sum

你可能感兴趣的:(leetcode,python编程技巧)