Editor

Maximum Subarray (Kadane)

Advanced · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write max_subarray(nums) that returns the largest sum of any non-empty run of consecutive numbers, in O(n).

max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])  ->  6   ([4, -1, 2, 1])
def max_subarray(nums):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])6
max_subarray([-3, -1, -2])-1

More practice problems

All Python exercises · 50 practice problems