Intuition

  • Through Kadanes Algorithm, you are checking in which case you should extend the current subarray, or just start a new subarray.
  • The idea is:
    • Make the greedy choice in each iteration.
      • Get the maximum between the current number or the current number plus the greedy maximum of before.
    • Then store the global maximum.
      • You need the global maximum since:
        • There is no guarantee that the locally maximum subarray sum you have found will not become larger as you move on to the next subarrays.
        • Likewise, there is no guarantee that the new subarray you have moved on to will have a larger globally optimal maximum subarray sum.
          • ex) [-2, 1, -3, 4, -1, 2, 1, -5, 4]
inums[i]Calculation of local_maxCalculation of reslocal_maxres
11max(1, -2 + 1) = 1max(-2, 1) = 111
2-3max(-3, 1 - 3) = -2max(1, -2) = 1-21
34max(4, -2 + 4) = 4max(1, 4) = 444
4-1max(-1, 4 - 1) = 3max(4, 3) = 434
52max(2, 3 + 2) = 5max(4, 5) = 555
61max(1, 5 + 1) = 6max(5, 6) = 666
7-5max(-5, 6 - 5) = 1max(6, 1) = 616
84max(4, 1 + 4) = 5max(6, 5) = 656

Complexity

Runtime

simple for loop

Space

no axillary space

Code

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        global_max = nums[0]
        local_max = nums[0]
        for i in range(1, len(nums)):
            if nums[i] + local_max >= nums[i]:
                local_max += nums[i]
            else: # reset
                local_max = nums[i]
            global_max = max(global_max, local_max)
            
        return global_max

Cards

START Basic Front: Maximum Subarray Back: Store the current element or the previous maximum’s the current element.

END


References