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