A Python solution


  • 59
    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
    

  • 0
    J

    Just a little shorter,

    class Solution(object):
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            max_sub,fn = nums[0],0
            for i in nums:
                fn = max([i,fn+i])
                max_sub = max(max_sub,fn)
            return max_sub
    

  • 0
    K

    @Google I had the same solution; the

    if not A:
        return 0
    

    edge case is actually not needed to make the tests pass, since it is given in the question that the array should have at least one number.


Log in to reply
 

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