2018-06-15 LeetCode53

2018-06-15  本文已影响0人  Betrayer丶

题目描述

我的解法

O(n)的复杂度,sum[i]=max{sum[i-1] + a[i], a[i]}

class Solution:
    def maxSubArray(self, nums):
        sums=nums[0]
        s=0
        for i in range(len(nums)):
            if s > 0:
                s=s+nums[i]
            else:
                s=nums[i]
            if sums < s:
                sums=s
        return sums

最优解法

class Solution:
    def maxSubArray(self, nums):
        sum = 0
        max = nums[0]
        
        for index in range(len(nums)):
            if sum < 0:
                sum = 0

            sum += nums[index]
            
            if sum > max:
                max = sum
        
        return max
上一篇 下一篇

猜你喜欢

热点阅读