#53

Maximum Subarray

Medium Kadane

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the contiguous non-empty subarray with the largest sum and return the sum.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the contiguous piece with the biggest sum.

Why this works: a running sum that has gone negative only drags down whatever comes next, so start over from the current number.

Example: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

cur: -2, 1, -2, 4, 3, 5, 6, 1, 5best = 6 → [4, -1, 2, 1]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Starting best at 0 — if every number is negative, the answer is the largest negative, not 0.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Kadane, Dutch Flag & Moore's Voting
🎬 Episodes 11–13: video coming soon