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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based Algorithms Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Algorithms Foundations books — check the publication year so the examples match current versions.
Search Amazon →