SDE & MLE Prep

53. Maximum Subarray

Problem

Return the largest sum of any non-empty contiguous subarray of nums.

Example: [-2,1,-3,4,-1,2,1,-5,4] → 6 ([4,-1,2,1]); [-1] → -1

Constraints: n ≤ 10⁵. Follow-up: a divide-and-conquer solution.

Kadane: the best subarray ending at i either extends the previous one or starts fresh at i.

nums  -2  1  -3  4  -1  2  1  -5  4
cur   -2  1  -2  4   3  5  6   1  5
best  -2  1   1  4   4  5  6   6  6

Complexity: O(n) time, O(1) space.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        best = cur = nums[0]
        for x in nums[1:]:
            cur = max(x, cur + x)
            best = max(best, cur)
        return best