←
Lens · Kadane's Algorithm · Any length

Biggest sum of numbers in a row

-20
11
-32
43
-14
25
16
-57
48
current run
–
best
–
The goalFind the biggest sum of numbers in a row (at least one).
1 / 19

Code

O(n) time · O(1) space
1def max_subarray(nums):2    current = best = nums[0]3    for x in nums[1:]:4        current = max(x, current + x)5        best = max(best, current)6    return best
WHY IT WORKSA run with a negative sum can only make what comes next smaller. Drop it and start fresh.