Kadane's Algorithm

Find the contiguous subarray with the largest sum in one pass: at each element, either extend the best subarray that ends just before it or start over.

Overview

The idea

The maximum subarray problem asks for the contiguous run of elements with the largest sum. Checking every run costs O(n²) time, and there are n(n + 1) / 2 of them: about 5 billion for n = 100,000.

Kadane's algorithm does it in one pass with two numbers. current is the largest sum of any subarray that ends at the element you are looking at. best is the largest current seen so far. At each element there are only two choices: extend the subarray that ends just before it, or start a new one here.

So at each element nums[i], the algorithm asks one question: is current + nums[i] larger than nums[i] alone?

  • If it is, the carry from the left is positive, so extend: current = current + nums[i].
  • If it is not, the carry is negative, so start over: current = nums[i].
  • Either way, set best = max(best, current), then move on to the next i.

If the sum carried in from the left is negative, it can only pull the new subarray down, so the algorithm drops it and starts fresh. The rule in one line is current = max(nums[i], current + nums[i]). The two branches differ only in whether current from the left is added, and adding it helps exactly when it is positive.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio