roadmap/dynamic-programming/Maximum Subarray

Maximum Subarray

MediumAmazonGoogleMicrosoftApple
Solve on LeetCode ↗

Given an integer array nums, find the subarray with the largest sum and return the sum.

Kadane's algorithm: at each position, decide whether to extend the previous subarray or start fresh. If the running sum becomes negative, it only hurts future elements — reset to 0.

Kadane's algorithm

curr = 0, best = nums[0]. For each num: curr = max(num, curr+num). best = max(best, curr). Return best.

Time
O(n)
Space
O(1)

Single pass, two variables.

Python
def maxSubArray(self, nums: List[int]) -> int:
    curr = best = nums[0]
    for num in nums[1:]:
        curr = max(num, curr + num)
        best = max(best, curr)
    return best
All negative: return the least negative (largest single element)
Single element: return it directly
Progress is saved on this device