53. 最大子序和--easy

给定一个整数数组nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
If sum is non-positive, it has no contribution to the last result, so we just give up all the aggregation before and set sum as the the current item.

def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n=len(nums)
        ans=nums[0]
        sum=0
        for i in range(0,n):
            if sum>0:
                sum=sum+nums[i]
            else:
                sum=nums[i]
            ans=max(ans,sum)
        return ans
posted @ 2021-10-22 23:06  梦想家肾小球  阅读(34)  评论(0编辑  收藏  举报