DEV Community

Timevolt
Timevolt

Posted on

The Matrix Reloaded: Mastering Kadane's Algorithm from Zero to Hero

The Quest Begins (The "Why")

I remember the first time I saw a problem that asked for the “maximum sum subarray.” I stared at the array, tried every brute‑force combo I could think of, and ended up with an O(n²) solution that timed out on the biggest test case. It felt like I was trying to defeat a final boss with a wooden sword—frustrating, slow, and definitely not the hero move I wanted.

Why does this problem keep showing up in interviews? Because it’s a perfect litmus test for dynamic programming thinking: can you spot the optimal substructure, can you reuse work, and can you do it in linear time? If you can’t, you’ll keep grinding on the same loops over and over. I wanted to break out of that cycle, and that’s when Kadane’s algorithm became my secret weapon.

The Revelation (The Insight)

The “aha!” moment came when I stopped thinking about all subarrays and started asking a simpler question: What’s the best subarray that ends at position i?

If I know the answer for i‑1, extending it by arr[i] gives me a candidate: best_ending_here + arr[i]. But maybe arr[i] alone is better—if the previous sum is negative, dragging it down only hurts. So the best subarray ending at i is simply:

best_ending_here = max(arr[i], best_ending_here + arr[i])
Enter fullscreen mode Exit fullscreen mode

Now, the global answer is just the maximum of all those best_ending_here values as we sweep left‑to‑right.

Why does this work? Because any optimal subarray must end somewhere. When we reach that end index, we’ve already considered the best way to get there (either by starting fresh or by extending the previous best). No other subarray can beat it, otherwise we’d have missed a better ending earlier—contradiction. This is the classic optimal‑substructure property of DP, and it collapses an exponential search into a single pass.

It felt like grabbing the power‑up in Super Mario: suddenly I could jump over obstacles that used to block me.

Wielding the Power (Code & Examples)

The Struggle: Brute Force

def max_subarray_bruteforce(nums):
    best = float('-inf')
    for i in range(len(nums)):
        cur = 0
        for j in range(i, len(nums)):
            cur += nums[j]
            best = max(best, cur)
    return best
Enter fullscreen mode Exit fullscreen mode

O(n²) time, O(1) space. Works fine for tiny inputs, but fails the moment n hits 10⁴.

The Victory: Kadane’s Algorithm

def max_subarray_kadane(nums):
    # Handles all‑negative arrays by starting with first element
    best_ending_here = best_so_far = nums[0]

    for x in nums[1:]:
        # Either extend the previous subarray or start fresh at x
        best_ending_here = max(x, best_ending_here + x)
        best_so_far = max(best_so_far, best_ending_here)

    return best_so_far
Enter fullscreen mode Exit fullscreen mode

Why this is O(n):

  • One loop, constant work per iteration → Θ(n).
  • Only two integer variables → O(1) extra space.

Common Traps (the “boss attacks” to dodge)

Trap What happens Fix
Resetting best_ending_here to 0 when it becomes negative Fails when all numbers are negative (returns 0 instead of the largest (least negative) element) Initialize with the first element and use max(x, best_ending_here + x) as shown
Forgetting to update best_so_far inside the loop You’ll return the value of the last best_ending_here, which may not be the global max Update best_so_far on every iteration

Interview Problem #1: Maximum Subarray (LeetCode 53)

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

Output: 6 (subarray [4,-1,2,1])

Running Kadane on this array yields 6 in a single pass—exactly what the interviewer expects.

Interview Problem #2: Best Time to Buy and Sell Stock I (LeetCode 121)

Input: prices = [7,1,5,3,6,4]

Output: 5 (buy at 1, sell at 6)

If you think of profit = price - min_price_so_far, it’s the same DP pattern: keep the smallest price seen (the “best ending here” for a buy) and compute the best profit ending at each day.

def max_profit(prices):
    min_price = prices[0]
    max_profit = 0
    for p in prices[1:]:
        min_price = min(min_price, p)
        max_profit = max(max_profit, p - min_price)
    return max_profit
Enter fullscreen mode Exit fullscreen mode

Again, O(n) time, O(1) space—just a slight reframing of Kadane.

Why This New Power Matters

Now you can walk into any interview and say, “I’ll solve this in linear time,” and actually deliver it. Beyond interviews, Kadane’s mindset trains you to look for local optimal decisions that build up to a global answer—a skill that shows up in segmentation, resource allocation, and even in signal processing.

You’ve moved from hammering away with nested loops to wielding a precise, elegant tool. That’s the kind of shift that makes you feel like you’ve leveled up from a side‑quest grunt to the main‑character hero.

Your Turn: The Next Challenge

Try adapting Kadane to a 2‑D matrix to find the maximum‑sum sub‑rectangle (hint: fix left and right columns, compress rows, then run Kadane on the compressed array). Or, tackle the “maximum subarray sum with at least one element” variant where you also need to return the actual indices.

Drop your solution or questions in the comments—I’d love to see how you’re leveling up! Happy coding!

Top comments (0)