DP Python Solution


  • 0
    M
    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            
            ret=-9999
            prevsum=nums[0]
            
            for i in range(1,len(nums)):
                prevsum=max(nums[i],nums[i]+prevsum)
                ret=max(ret,prevsum)
    
            ret=max(nums[0],ret)
            
            return ret
    

    Every time to calculate the max sum starting from 0 end with n, we either take sum(nums[0:n-1])+nums[n] or nums[n], whichever is larger. In other words, if sum(nums[0:n-1)] is less than 0, than we will drop the nums[0:n-1].


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.