Maximum Subarray with Kadane’s Algorithm
Compare the best sum ending at the current index with the best sum seen overall.
Core Intuition & How It Works
Kadane’s algorithm finds the contiguous subarray with the largest sum in a single linear pass. At each element, it decides whether to extend the previous best subarray or start fresh at the current element.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 3: Array & String Techniques |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Maintain currentBest = max(x, currentBest + x) and globalBest = max(globalBest, currentBest) at each index.
Common Pitfalls & Edge Cases
Initializing globalBest to 0 instead of the first element, which returns the wrong answer when all array values are negative.
Real-World & Technical Interview Applications
Maximum profit windows, signal processing peak detection, and 2D maximum submatrix reductions.