AlgoFrames

Kadane's algorithm and maximum subarray

Kadane’s algorithm finds the maximum subarray in one pass by tracking the best sum ending here and the best seen so far.

Before you start: 1-D DP: house robber, decode ways, jump game II.

The idea

A shop records its profit or loss each day. Which run of consecutive days earned the most in total?

Intuition

Summing every run works but is slow. Nine values already give 45 runs, and the count grows with n².

A run is fixed by its first and last index. There are n(n + 1) / 2 such pairs.

A run that sums below 0 only drags down what follows. At 4, starting fresh beats carrying −4.

The best run ending at i either extends the best run ending at i − 1 or starts at i. Extending helps only when that earlier sum is positive.

Complexity

Kadane looks at each value once: O(n) time. Summing every run takes O(n²) even with running sums.

The y axis is logarithmic. At 40 values there are 820 runs but only 40 Kadane steps.

Only two numbers are kept, cur and best. The table of sums ending at each index is never stored: O(1) space.

Pitfalls

Starting best at 0 returns 0 when every value is negative. Start cur and best at the first value.

A subarray must hold at least one value. 0 stands for the empty run, which is not allowed here.

Returning cur gives the best run ending at the last index, 5 here. Update best at every step and return it.

Variations

Buy and sell once: track the cheapest price so far. Selling today earns the price minus that minimum.

On a circle, a wrapping run is the total minus the smallest inside run. Run Kadane for the maximum and the minimum.

For the largest product, keep the smallest product too. A negative value turns the smallest into the largest.

Code

Pseudocode

maxSubarray(a):
  cur ← a[0], best ← a[0]
  for i ← 1 to n - 1
    cur ← max(a[i], cur + a[i])
    best ← max(best, cur)
  return best

Python

def max_subarray(nums):
    cur = best = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

JavaScript

function maxSubArray(nums) {
  let cur = nums[0], best = nums[0];
  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]);
    best = Math.max(best, cur);
  }
  return best;
}

Java

static int maxSubArray(int[] nums) {
    int cur = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        cur = Math.max(nums[i], cur + nums[i]);
        best = Math.max(best, cur);
    }
    return best;
}

Practice problems (6)

Predict Kadane's answer Warm-up

What does this code print?

Follow Kadane's two numbers Warm-up

Follow Kadane's algorithm on 1, −3, 2, 1, −1. Answer each question before the step plays.

Maximum subarray Standard

Return the largest sum of a contiguous, non-empty subarray of nums.

Best time to buy and sell once Standard

prices[i] is a stock's price on day i. Buy one share on one day and sell it on a later day.

Return the largest profit you can make, or 0 if no trade makes money.

Maximum circular subarray Standard

nums is circular: after the last value comes the first again. A subarray may wrap past the end, but it may use each value at most once.

Return the largest sum of a non-empty subarray.

Maximum product subarray Challenge

Return the largest product of a contiguous, non-empty subarray of nums.

The answer fits in a 32-bit signed integer.

Related topics

Next on the path: 0/1 and unbounded knapsack