码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-easy-dynamic-53 Maximum Subarray

时间:2019-06-10 18:48:16      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:col   更新   +=   最大和   pre   range   bsp   sub   列表   

mycode  66.85%

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = resmax = 0
        flag = -1
        for i in range(len(nums)):
            if nums[i] < 0 :
                if res+nums[i] <= 0:                
                    res = 0
                else:                    
                    res += nums[i]
            if nums[i] > 0:
                flag = 1
                res += nums[i]
            resmax = max(resmax,res)
        if flag == -1:
            return max(nums)
        return resmax
             
        
        

 

参考

思路和上面是一样的,但是初始化不一样,所以不用单独去考虑列表中都为负数的情况

before用来记录短期的最大和,一旦自身变为了负数,就更新为当前值

res一直要去比较和before的大小,来更新为最大值

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res=before=nums[0]
        for num in nums[1:]:
            if before>=0:
                before=before+num
            else:
                before=num
            if res<before:
                res=before
        return res

 

leetcode-easy-dynamic-53 Maximum Subarray

标签:col   更新   +=   最大和   pre   range   bsp   sub   列表   

原文地址:https://www.cnblogs.com/rosyYY/p/10999381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!