intermediate7 min read·Updated September 17, 2026

Kadane's Maximum Subarray Explained: Tracing [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Master Kadane's Algorithm with a complete mental model and step-by-step trace of [-2, 1, -3, 4, -1, 2, 1, -5, 4] and all-negative arrays.

By Learnisim AI·Published September 17, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • Basic arrays
  • For loops
Kadane's Algorithm: Max Subarray & Edge Cases Main Array Trace: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] -2 i=0 1 i=1 -3 i=2 4 i=3 (Start) -1 i=4 2 i=5 1 i=6 (End) -5 i=7 4 i=8 Max Subarray: [4, -1, 2, 1] ➔ Sum = 6 cur = max(val, cur + val) Extend or Fresh Start best = max(best, cur) Global Record (Max Sum = 6) Single pass O(n) time, O(1) space: drops negative past baggage instantly. Edge Case: All-Negative Input nums = [-1, -2, -3] -1 -2 -3 Naive zero-default fails here (returns 0). Kadane correctly picks maxSum = -1 (The single least damaging element is chosen). Why Brute Force Fails Combinatorial Explosion Subarray count = N(N+1)/2 45 slices for N=9 elements Billions of ops for N=100k Redundant Overlaps Recomputing window sums O(n²) nested loops drag Slow & wasteful performance Kadane's Breakthrough Single pass O(n) scan Local decision at each step Optimal & handles negatives
Max subarray of [-2, 1, -3, 4, -1, 2, 1, -5, 4] vs [-1, -2, -3] overview diagram
Why

Why Brute Force Fails on Maximum Subarray Problems

Imagine you are handed the sequence and asked to find the contiguous subarray that yields the largest possible sum. If you approach this with a naive brute-force mindset, you might think of checking every single starting and ending index combination. With elements, there are possible subarrays, which explodes quickly as grows. For our specific array of 9 elements, that means evaluating 45 distinct slices. If your array scales to 100,000 elements, brute force requires billions of operations, dragging performance down to a crawl. Worse yet, what happens when you encounter an array like where every number is negative? A naive approach that defaults to an empty sum of 0 will completely fail the constraint that at least one element must be selected. Kadane's maximum subarray explained starts right here: how do we inspect every relevant contiguous slice in a single pass without recomputing sums from scratch?
Why Brute Force Fails on Maximum Subarray Problems Comparing O(N^2) Combinatoric Slice Explosions vs. Negative Edge Cases 1. Combinatoric Explosion: O(N²) Array nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] (N = 9) Possible Subarrays = N(N+1)/2 = 9(10)/2 = 45 slices Nested loop pointer scans (i, j) -2 1 -3 4 -1 2 1 -5 4 Evaluates 45 overlapping slices redundantly The Scaling Bottleneck N = 100,000 elements → ~5 BILLION slice checks! Nested loops recompute sums from scratch every time. ⚠ Inefficient: O(N²) time complexity Kadane's reduces this to a single O(N) linear pass. 2. The All-Negative Array Trap Edge Case: nums = [-1, -2, -3] -1 -2 -3 Every single number is strictly negative ❌ The Naive Default = 0 Bug If max_sum initializes to 0 assuming positive values, it returns 0 (empty subarray)! Constraint violation: subarray cannot be empty. ✅ Kadane's Correct Handling Initialize accumulator to nums[0] (-1), not 0. Correct maximum subarray sum = -1 (just [-1]) Tracks single least-negative element correctly. WHY
Why Brute Force Fails on Maximum Subarray Problems diagram
Model

Building the Mental Model for Kadane's Algorithm

When examining our running target array , a naive slice check forces us to recompute overlapping windows repeatedly. Kadane's algorithm replaces this redundancy with a dynamic programming mindset, asking a single local question at each index : do I extend the previous running subarray, or do I drop it and start a fresh subarray right here?
Let be the maximum sum of a subarray ending at the current position, and be the global maximum found so far across the entire sequence. As we step through elements from left to right, updates via . If the accumulated ever drops below the standalone value of , it means dragging along the old history hurts more than it helps—so we jettison the past and restart our subarray at . This exact mechanism also protects us when handling our second test case, , ensuring we pick the least damaging single element rather than mistakenly settling on a default sum of 0.
Kadane's Algorithm: Max Subarray DP State Machine Local Choice: cur = max(nums[i], cur + nums[i]) | Global: best = max(best, cur) Primary Target Array (Indices 0 to 8) -2 i:0 | cur:-2 1 restart(1) -3 cur:-2 4 restart(4) -1 cur:3 2 cur:5 1 cur:6 (best) -5 cur:1 4 cur:5 Max Subarray sum = 6 The Two Choices at Every Step 1. Extend Previous Subarray cur = cur + nums[i] (Carry forward past momentum) 2. Jettison & Restart Here cur = nums[i] (History hurts more than it helps) Edge Case: nums = [-1, -2, -3] Why initializing best = 0 fails on all-negative arrays: -1 cur:-1 -2 cur:-2 -3 cur:-3 Safeguard Rule: Initialize best = nums[0] (not 0). Result correctly returns single max element -1.
Building the Mental Model for Kadane's Algorithm diagram
Worked example

Tracing Kadane's Algorithm Step by Step on [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Let us execute our model on the primary array from our locked example: . We track two variables at every index : , which decides whether to extend the previous subarray or start fresh at , and , which records the global record seen so far.
Given: . We initialize both and using the first element.
Steps:
* : . (We dropped because starting fresh at 1 is better). .
* : . .
* : . (We dropped the negative baggage accumulated so far). .
* : . .
* : . .
* : . .
* : . .
* : . .
Result: The maximum contiguous subarray sum is 6, generated by the slice .
Try this: Trace the same step-by-step logic for the secondary locked array nums = [-1, -2, -3]. What will maxSum be after processing the final element -3?
Tracing Kadane's Algorithm Step by Step nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] | Tracking currentSum & maxSum i=0 -2 i=1 1 i=2 -3 i=3 4 i=4 -1 i=5 2 i=6 1 i=7 -5 i=8 4 Max Subarray sum: 6 currentSum Decision Rule Decides whether to extend or restart fresh: currentSum = max(val, currentSum + val) maxSum Global Tracker Records the highest sum encountered so far: maxSum = max(maxSum, currentSum) Key Insight from Trace: At i = 3 (val = 4), negative baggage (-2) is dropped: max(4, -2 + 4) = 4 Final Result: maxSum reaches 6, generated by the contiguous subarray slice [4, -1, 2, 1].
Tracing Kadane's Algorithm Step by Step on [-2, 1, -3, 4, -1, 2, 1, -5, 4] diagram
Practice

Putting Kadane's Algorithm to the Test on All-Negative Inputs

Now that you have seen how Kadane's algorithm traces through the mixed sequence to find a maximum sum of 6, it is time to test your grasp of the update rules on the second half of our locked example: the all-negative sequence .
Recall that and . If you initialize and to the first element instead of zero, you avoid the trap of returning an empty subarray sum of 0.
Work through the array element by element, tracking what and become after each step.
Try this: Given nums = [-1, -2, -3].
1.Initialize: cur = nums[0], best = nums[0]
2.Step 1 (x = -2): cur = max(-2, cur + (-2)), best = max(best, cur)
3.Step 2 (x = -3): cur = max(-3, cur + (-3)), best = max(best, cur)

What are the final values of cur and best?
Apply

Transferring Kadane's Thinking to Peak Profit and Stream Processing

The pattern we uncovered while tracking and is not just for finding contiguous sums in static arrays. Whenever you need to find a maximum contiguous window where local decisions either anchor a new start or extend an existing run, this exact dynamic programming skeleton applies. For instance, consider finding the maximum profit from daily price changes instead of raw numbers, or processing an infinite real-time telemetry stream where memory is bounded and you can only keep running counters. The core insight—that a negative running accumulator should be dropped because it hurts any future contribution—translates directly to any domain dealing with local drag versus explosive upside.
python
def max_subarray_profit_stream(price_changes):
    # TODO: Apply Kadane's tracking to price changes
    pass

FAQ

What is the maximum subarray sum for [-2, 1, -3, 4, -1, 2, 1, -5, 4] using Kadane's algorithm?
The maximum sum is 6, generated by the subarray [4, -1, 2, 1].
How does Kadane's algorithm handle arrays where all numbers are negative, like [-1, -2, -3]?
Kadane's algorithm correctly returns the maximum single element, which is -1, rather than defaulting to 0, provided the current max and global max are initialized to the first element rather than 0.
What is the time and space complexity of Kadane's algorithm?
Kadane's algorithm runs in O(n) time with a single pass through the array and O(1) auxiliary space, making it optimal for the maximum subarray problem.

Keep learning