Python 3 Solution 97.63%


  • 0
    D
    class Solution:
        def maxSubArray(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if len(nums) == 0:
                return 0
            elif len(nums) == 1:
                return nums[0]
            else:
                max_sum = nums[0]
                current_max = max_sum
                tail = nums[1:]
                for num in tail:
                    if current_max < 0:
                        current_max = num
                    else:
                        current_max = current_max + num
                    
                    if current_max > max_sum:
                        max_sum = current_max
                return max_sum 
    

    Some findings:

    • if-else is faster than max(v1, v2)
    • if-else is faster than v = v1 if condition else v2

    The code is O(n).


Log in to reply
 

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