leetcode-easy-dynamic-53 Maximum Subarray
Posted rosyyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-easy-dynamic-53 Maximum Subarray相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章