Python 7 lines O(1) space solution - easy to understand, beats 94%


  • 0
    N

    If the cumulative sum reaches a negative number, you can start a new subarray. Keep track of all the maximum sum. If the maximum sum turns out to be 0, then it means there is no positive number in the array, so simply return the maximum number.

        def maxSubArray(self, nums):
            sum, maxSum = 0, 0
            for n in nums:
                sum += n
                if sum < 0:
                    sum = 0
                maxSum = max(maxSum, sum)
            return maxSum if maxSum > 0 else max(nums)
    

Log in to reply
 

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