BeginnerCoder

Lesson 16 — Max subarray

Kadane's algorithm: the best stretch

A subarray is a run of neighbouring items. Which run has the biggest sum? Kadane's trick: walk once, keeping cur = the best sum of a run that ends here. At each item, either extend the previous run (cur + x) or start fresh at x — whichever is bigger. Track the overall best.

run = max(item, run + item)   # start fresh, or extend
top = max(top, run)           # remember the best so far

Why it matters: "best profit window" or "strongest streak" questions are solved in one O(n) pass instead of checking every pair of start and end.

Want it another way?
Task

Write the two update lines from the theory (Kadane). Expected: 6 (the run 4, -1, 2, 1), then -1.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Algorithms Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.