Video in progress

Strong Middle 🧠 Problem solving

How does Kadane's algorithm work, and what happens if all the numbers in the array are negative?

At each position we keep "the best sum ending here": either we add to the previous one, or we start over from this element. The answer is the maximum of those. Written correctly, when everything is negative it returns the largest (smallest in absolute value) negative number.

📖 Answer

static long maxSubarray(int[] a) {
    long cur = a[0], best = a[0];
    for (int i = 1; i < a.length; i++) {
        cur = Math.max(a[i], cur + a[i]);   // do we continue or start fresh
        best = Math.max(best, cur);
    }
    return best;
}

A commonly seen wrong version starts with best = 0, cur = 0 and resets to zero when cur < 0. On [-3, -1, -2] it returns 0, which means it treats the empty subarray as the answer. If the problem allows an empty subarray, that's correct; otherwise it's a bug. Ask the interviewer.

This is really the simplest DP: dp[i] = max(a[i], dp[i-1] + a[i]), with no array because only the previous value is needed.

Extensions:

  • if you need the range itself, you remember the index where cur last restarted;
  • circular array: the answer is either ordinary Kadane or total − minimum subarray. If everything is negative, the second variant gives the empty set, so that needs a separate check;
  • maximum product: negative × negative = positive, so you track both the maximum and the minimum.

A practical reading: the most profitable contiguous period in a list of daily profit and loss. If you work with money, keep the sum in a long (in minor units) or in a BigDecimal.