Lesson 2 · Problem-solving methods

Kadane's Algorithm

Kadane's algorithm finds the contiguous subarray with the largest sum in one pass, by keeping the best sum that ends at the current index and the best seen so far.

Kadane's Algorithm concept diagramThe array -2, 1, -3, 4, -1, 2, 1, -5, 4 with two rows below it: cur, the best sum ending at each index, and best, the running maximum. Restart cells at indices 0, 1 and 3 are orange. A bracket under indices 3 to 6 marks the maximum subarray 4, -1, 2, 1 with sum 6.012345678a[i]curbest-2-2-2111-3-21444-134255166-516456ending hereso farmaximum subarray: 4 + (−1) + 2 + 1 = 6cur = max(a[i], cur + a[i]) · best = max(best, cur) · orange cells: cur + a[i] < a[i], so restart
1

The Problem and the Idea

  1. State – cur is the largest sum of a subarray that ends at index i; best is the largest sum seen anywhere so far.
  2. Start – set cur = best = a[0].
  3. Decide – at each later index, either extend the current run (cur + a[i]) or restart at a[i], whichever is larger.
  4. Record – best = max(best, cur). After the last index, best is the answer.

Kadane's algorithm solves the maximum subarray problem: given an array of integers, some of them negative, find the contiguous subarray with the largest sum. For [−2, 1, −3, 4, −1, 2, 1, −5, 4] the answer is 6, from the subarray [4, −1, 2, 1].

It reads the array once, left to right, and keeps just two numbers. That makes it the standard example of dynamic programming reduced to constant space: each step depends only on the step before it.

  • Subarray means contiguous; a subsequence may skip elements and is a different problem
  • Textbooks also call it the largest sum contiguous subarray problem
  • Named after Jay Kadane, who gave the linear-time solution in 1977
2

Why Dropping a Negative Sum Works

Every subarray ends somewhere. If we knew, for each index i, the best sum of a subarray ending exactly at i, the answer would be the largest of those values. Call that value cur(i).

A subarray ending at i is either a[i] alone, or a[i] appended to some subarray ending at i − 1. The best of the second kind is cur(i − 1) + a[i]. So cur(i) = max(a[i], cur(i − 1) + a[i]). Only the previous cur is needed, so one variable is enough.

The rule has a simple reading: if the running sum is negative, drop it. A negative prefix can only make whatever follows smaller, so starting fresh at a[i] is always at least as good. A positive prefix, however small, is always kept.

  • Recurrence: cur(i) = max(a[i], cur(i − 1) + a[i])
  • Answer: max over i of cur(i)
  • Equivalent test: restart exactly when cur(i − 1) < 0
3

Complexity and Other Approaches

The scan does one comparison and one addition per element, so it runs in O(n) time and uses O(1) extra space. No algorithm can do better, because every element must be read at least once: any unread element could be a huge positive number.

The other known approaches all do more work. Brute force sums every subarray; a running sum brings that down to O(n²); divide and conquer splits the array, solves each half, and handles the subarray that crosses the middle in O(n log n).

Approaches to the maximum subarray problem
ApproachIdeaTimeSpace
Brute forcesum every subarray from scratchO(n³)O(1)
Better brute forceextend a running sum from each startO(n²)O(1)
Divide and conquerbest of left half, right half, and crossing the middleO(n log n)O(log n)
Kadane's algorithmbest sum ending at each indexO(n)O(1)
  • O(n) time is optimal: every element must be examined
  • O(1) space: only cur, best and, optionally, two indices
  • Works on a stream, since it never looks back
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Maximum subarray problemFind the contiguous run with the largest sum.
  • curBest sum of a subarray ending exactly at the current index.
  • bestLargest cur seen so far; the answer after the last index.
  • RestartDrop a negative running sum and begin a new run at a[i].

Formulas

  • Recurrencecur(i) = max(a[i], cur(i − 1) + a[i]).
  • Answermax over all i of cur(i).
  • TimeO(n), one pass.
  • SpaceO(1): cur, best and two indices.
Implementation

Code in Python, C++ and Java

def max_subarray(nums):
    best = cur = nums[0]
    start = best_start = best_end = 0
    for i in range(1, len(nums)):
        if cur + nums[i] < nums[i]:
            # A negative running sum only drags nums[i] down: restart here.
            cur = nums[i]
            start = i
        else:
            cur += nums[i]
        if cur > best:
            best, best_start, best_end = cur, start, i
    return best, best_start, best_end


def brute_force(nums):
    n = len(nums)
    return max(sum(nums[i : j + 1]) for i in range(n) for j in range(i, n))


def trace(nums):
    print(" i  a[i]   cur  best  action")
    cur = best = nums[0]
    print(f"{0:>2}  {nums[0]:>4}  {cur:>4}  {best:>4}  start")
    for i in range(1, len(nums)):
        action = "restart" if cur + nums[i] < nums[i] else "extend"
        cur = max(nums[i], cur + nums[i])
        best = max(best, cur)
        print(f"{i:>2}  {nums[i]:>4}  {cur:>4}  {best:>4}  {action}")


def show(values):
    return "[" + ", ".join(str(v) for v in values) + "]"


trace([-2, 1, -3, 4, -1, 2, 1, -5, 4])
print()
for nums in [
    [-2, 1, -3, 4, -1, 2, 1, -5, 4],
    [5, 4, -1, 7, 8],
    [-3, -1, -2],
    [2, -1, 2, -1, 2],
    [7],
]:
    best, lo, hi = max_subarray(nums)
    ok = best == brute_force(nums)
    print(
        f"{show(nums)} -> {best} from {show(nums[lo : hi + 1])} "
        f"(indices {lo}..{hi}), brute force agrees: {ok}"
    )
#include <algorithm>
#include <cstdio>
#include <string>
#include <tuple>
#include <vector>

std::tuple<int, int, int> maxSubarray(const std::vector<int>& nums) {
    int best = nums[0], cur = nums[0];
    int start = 0, bestStart = 0, bestEnd = 0;
    for (int i = 1; i < (int)nums.size(); i++) {
        if (cur + nums[i] < nums[i]) {
            // A negative running sum only drags nums[i] down: restart here.
            cur = nums[i];
            start = i;
        } else {
            cur += nums[i];
        }
        if (cur > best) {
            best = cur;
            bestStart = start;
            bestEnd = i;
        }
    }
    return {best, bestStart, bestEnd};
}

int bruteForce(const std::vector<int>& nums) {
    int best = nums[0];
    for (size_t i = 0; i < nums.size(); i++) {
        int sum = 0;
        for (size_t j = i; j < nums.size(); j++) {
            sum += nums[j];
            best = std::max(best, sum);
        }
    }
    return best;
}

void trace(const std::vector<int>& nums) {
    std::printf(" i  a[i]   cur  best  action\n");
    int cur = nums[0], best = nums[0];
    std::printf("%2d  %4d  %4d  %4d  start\n", 0, nums[0], cur, best);
    for (int i = 1; i < (int)nums.size(); i++) {
        const char* action = cur + nums[i] < nums[i] ? "restart" : "extend";
        cur = std::max(nums[i], cur + nums[i]);
        best = std::max(best, cur);
        std::printf("%2d  %4d  %4d  %4d  %s\n", i, nums[i], cur, best, action);
    }
}

std::string show(const std::vector<int>& v, int lo, int hi) {
    std::string s = "[";
    for (int i = lo; i <= hi; i++) s += (i > lo ? ", " : "") + std::to_string(v[i]);
    return s + "]";
}

int main() {
    trace({-2, 1, -3, 4, -1, 2, 1, -5, 4});
    std::printf("\n");
    std::vector<std::vector<int>> tests = {
        {-2, 1, -3, 4, -1, 2, 1, -5, 4}, {5, 4, -1, 7, 8}, {-3, -1, -2}, {2, -1, 2, -1, 2}, {7}};
    for (const auto& nums : tests) {
        auto [best, lo, hi] = maxSubarray(nums);
        bool ok = best == bruteForce(nums);
        std::printf("%s -> %d from %s (indices %d..%d), brute force agrees: %s\n",
                    show(nums, 0, (int)nums.size() - 1).c_str(), best, show(nums, lo, hi).c_str(), lo,
                    hi, ok ? "True" : "False");
    }
}
public class Main {
    static int[] maxSubarray(int[] nums) {
        int best = nums[0], cur = nums[0];
        int start = 0, bestStart = 0, bestEnd = 0;
        for (int i = 1; i < nums.length; i++) {
            if (cur + nums[i] < nums[i]) {
                // A negative running sum only drags nums[i] down: restart here.
                cur = nums[i];
                start = i;
            } else {
                cur += nums[i];
            }
            if (cur > best) {
                best = cur;
                bestStart = start;
                bestEnd = i;
            }
        }
        return new int[] {best, bestStart, bestEnd};
    }

    static int bruteForce(int[] nums) {
        int best = nums[0];
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                best = Math.max(best, sum);
            }
        }
        return best;
    }

    static void trace(int[] nums) {
        System.out.println(" i  a[i]   cur  best  action");
        int cur = nums[0], best = nums[0];
        System.out.printf("%2d  %4d  %4d  %4d  start%n", 0, nums[0], cur, best);
        for (int i = 1; i < nums.length; i++) {
            String action = cur + nums[i] < nums[i] ? "restart" : "extend";
            cur = Math.max(nums[i], cur + nums[i]);
            best = Math.max(best, cur);
            System.out.printf("%2d  %4d  %4d  %4d  %s%n", i, nums[i], cur, best, action);
        }
    }

    static String show(int[] v, int lo, int hi) {
        StringBuilder s = new StringBuilder("[");
        for (int i = lo; i <= hi; i++) s.append(i > lo ? ", " : "").append(v[i]);
        return s.append("]").toString();
    }

    public static void main(String[] args) {
        trace(new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4});
        System.out.println();
        int[][] tests = {{-2, 1, -3, 4, -1, 2, 1, -5, 4}, {5, 4, -1, 7, 8}, {-3, -1, -2}, {2, -1, 2, -1, 2}, {7}};
        for (int[] nums : tests) {
            int[] r = maxSubarray(nums);
            boolean ok = r[0] == bruteForce(nums);
            System.out.printf("%s -> %d from %s (indices %d..%d), brute force agrees: %s%n",
                    show(nums, 0, nums.length - 1), r[0], show(nums, r[1], r[2]), r[1], r[2], ok ? "True" : "False");
        }
    }
}
Watch it run

Step through it

Running on [-2, 1, -3, 4, -1, 2, 1, -5, 4], then [-3, -1, -2]

a[i]-2011-3243-142516-57480curfor each i: cur = max(a[i], cur + a[i]), best = max(best, cur)one pass, O(n) time, O(1) space
Step 1

The array: find the contiguous run with the largest sum

Nine values, some negative. A brute-force search tries all 45 subarrays; this scan reads each value once and keeps only two numbers: cur, the best sum of a subarray that ends exactly here, and best, the largest cur seen so far.

Output
1 / 13
4

A Worked Run on Nine Values

Run it on [−2, 1, −3, 4, −1, 2, 1, −5, 4]. cur starts at −2. At index 1 the run so far is negative, so cur restarts at 1. Index 2 pulls it to −2, which is still better than −3 alone, so the run extends. At index 3 the run is negative again and cur restarts at 4.

From there cur goes 3, 5, 6, 1, 5 and never drops below zero, so the run starting at index 3 is never abandoned. best follows cur up to 6 at index 6 and stays there. The tracer above shows every index.

  • Answer: 6, from indices 3 to 6: [4, −1, 2, 1]
  • Index 4 shows why a dip is kept: 3 is still positive and pays off at index 5
  • Index 7 drops cur to 1, but a positive run is never abandoned
5

Returning the Subarray, Not Just the Sum

To report which elements form the maximum subarray, keep one more index: start, where the current run began. Set start = i whenever the algorithm restarts. Whenever best improves, copy start and i into bestStart and bestEnd.

The listing above does exactly this and still uses O(1) space. Ties are broken by the first run to reach the best sum, because best only changes on a strictly larger value.

  • On restart: start = i
  • On improvement: bestStart = start, bestEnd = i
  • Use ≥ instead of > to prefer the last or longest tying run
6

All Negative Numbers and the Empty Subarray

If every element is negative, the best subarray is the single largest element: for [−3, −1, −2] the answer is −1. Kadane's algorithm handles this correctly only if cur and best start at a[0].

A common variant starts both at 0 and resets cur to 0 whenever it drops below zero. That version returns 0 on an all-negative array, which is the sum of the empty subarray. It is correct only when the problem says an empty subarray is allowed, so read the problem statement before choosing.

  • Non-empty subarray required: initialise with a[0]
  • Empty subarray allowed: initialise with 0
  • Test every implementation on an all-negative array
7

Problems That Reuse the Idea

The same best ending here idea solves a family of problems. Each keeps a small state per index and updates it from the previous one.

  • Minimum subarray sum: use min in place of max
  • Maximum circular subarray sum: a run that wraps around is the total minus the minimum subarray; take the larger of that and the plain answer, except when every value is negative (then use the plain answer)
  • Maximum product subarray: keep both the largest and smallest product ending here, since a negative value swaps them
  • Maximum sum rectangle in a 2D matrix: fix a pair of rows, add up each column between them into one array and scan it: O(rows² × cols)
  • Best time to buy and sell stock: the same scan over the day-to-day price changes
  • Practise the base problem: Maximum Subarray
  • Pattern: a state for 'best ending at i', updated from i − 1
  • Related prefix-sum view: max over j of prefix[j] − min prefix before j