[Lintcode]41. Maximum Subarray/[Leetcode]53. Maximum Subarray

41. Maximum Subarray/53. Maximum Subarray

  • 本题难度: Eas
  • Topic: Dynamic Programming

Description

Given an array of integers, find a contiguous subarray which has the largest sum.

Example
Example1:
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Example2:
Given the array [1,2,3,4], the contiguous subarray [1,2,3,4] has the largest sum = 10.

Challenge
Can you do it in time complexity O(n)?

Notice
The subarray should contain at least one number.

我的代码

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #Oct 10, 2018
        l = len(nums)
        if l == 0:
            return 0
        
        if l == 1:
            return nums[0]
        top = nums[0]
        tmp = top
        for i in range(1,l):
            if top<0 and nums[i]>top:
                top = nums[i]
                tmp = top
                continue
            if nums[i]+tmp>0:
                tmp = tmp + nums[i]
                if tmp>top:
                    top = tmp
            else:
                tmp = 0
        return top

别人的代码

for i in range(1, len(nums)):
        if nums[i-1] > 0:
            nums[i] += nums[i-1]
    return max(nums)

思路
那个别人的代码真个天才我的天哦

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10388349.html