Skip to content

Maximum Subarray

MediumLeetCode #53Time O(n)Space O(1)

Given an integer array (it may contain negatives), find the contiguous, non-empty subarray with the largest sum. Return the sum, not the subarray.

nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] -> 6 ([4, -1, 2, 1])

Brute force sums every subarray, which is O(n²) (or O(n³) if you re-add each one). The waste is recomputing overlapping sums.

Think about the best subarray that ends at index i. It either extends the best one ending at i-1, or starts fresh at i: cur[i] = max(nums[i], cur[i-1] + nums[i]). The answer is the max of cur over all i. If the running sum has gone negative, it can only hurt, so you drop it. That is Kadane’s algorithm. Only the previous cur is needed, so space is O(1).

Show solutionHide solution
def max_sub_array(nums: list[int]) -> int:
best = cur = nums[0] # cur = best sum of a subarray ending at i
for i in range(1, len(nums)): # nums[1:] would copy the list: O(n) space
cur = max(nums[i], cur + nums[i]) # extend the previous subarray, or restart here
best = max(best, cur)
return best
  • Time: O(n) — one pass, constant work per element.
  • Space: O(1) — two variables: cur and best.
  • All-negative input. Do not start best at 0 or reset cur to 0: for [-3, -1, -2] the answer is -1, not 0. Initialize both from nums[0].
  • Restart means nums[i] alone, not 0. The subarray must be non-empty.
  • Track best separately from cur. cur can drop after the peak, so returning it at the end is wrong.

Same question with products. The trick: a negative number flips the biggest to the smallest, so track both the max and min product ending at i, and take the best of nums[i], max*nums[i] and min*nums[i].

Maximum Sum Circular Subarray (LeetCode 918)

Section titled “Maximum Sum Circular Subarray (LeetCode 918)”

The array wraps around. The trick: the answer is either the normal Kadane result or total - (minimum subarray sum), where the wrapped part is everything outside a minimum subarray. If all numbers are negative, use the normal result.