Kadane's Algorithm
Find the maximum sum contiguous subarray in O(n) time. The quintessential dynamic programming problem that every FAANG interview expects you to know.
Kadane's Algorithm
Find the maximum sum contiguous subarray in O(n) time. The quintessential dynamic programming problem that every FAANG interview expects you to know.
Initialize: currentSum = maxSum = arr[0] = -2
Kadane in one pass
Order the steps for the maximum subarray sum.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
What decision does Kadane's algorithm make at each element?
The short version
Imagine you're tracking your stock portfolio. At each day, you decide: 'Should I keep adding to my current streak, or cut losses and start fresh?' Kadane's makes this decision at every step.
In more depth
The Core Insight
At each position, we have two choices:
We choose whichever gives a larger sum.
Recurrence:
currentSum = max(arr[i], currentSum + arr[i])
maxSum = max(maxSum, currentSum)Why It Works
If the running sum becomes negative, it can only hurt future subarrays. Better to start fresh!
When to reach for this
- Find maximum/minimum contiguous subarray
- Optimization over all subarrays
- Keywords: 'contiguous', 'subarray', 'maximum sum'
Interview Questions
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required