python3 solution in O(n),no DP


  • 0
    R
    class Solution:
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
    
            if len(nums) == 1:
                return nums[0]
    
            max = nums[0]
            j = 0
            while True:
                if j >= len(nums) or nums[j] > 0:
                    break
    
                if nums[j] > max:
                    max = nums[j]
                j += 1
    
            tmp = 0
            for i in range(j, len(nums)):
                if nums[i] < 0:
                    if tmp + nums[i] > 0:
                        tmp += nums[i]
                    else:
                        tmp = 0
                else:
                    tmp += nums[i]
    
                if tmp > max:
                    max = tmp
    
            return max
    

Log in to reply
 

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