A Python solution


  • 52
    G
    class Solution:
        # @param A, a list of integers
        # @return an integer
        # 6:57
        def maxSubArray(self, A):
            if not A:
                return 0
    
            curSum = maxSum = A[0]
            for num in A[1:]:
                curSum = max(num, curSum + num)
                maxSum = max(maxSum, curSum)
    
            return maxSum

  • 0
    J

    very clear solution!


  • 0

    clearer than mine!

    #  48 ms
    def maxSubArray(self, A):
            max_sum = nums[0]
            csum = nums[0]
            for n in nums[1:]:
                csum = n if csum < 0 else csum + n
                if csum > max_sum:
                    max_sum = csum
            return max_sum
    

  • 0

    @Google Very nice.


  • 0

    A little revision to avoid copying the list.

    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
    
            maxSum = currentSum = -float("inf")
            for n in nums:           
                currentSum = max(currentSum+n, n)
                maxSum = max(maxSum, currentSum)
            return maxSum
    

  • 0
    S

    As the problem has mentioned that array (containing at least one number)
    so this part is not necessary literally

    if not A:
         return 0
    

  • 0

    better than mine

    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            t = s = m = nums[0]
            for i in nums:
                if i >= 0:
                    s = max(s, 0)
                else:
                    m = max(m, s)
                t = max(t, i)
                s += i
            return max(s, m) if t > 0 else t
    

Log in to reply
 

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