Skip to lesson

Maximum subarray: Kadane's algorithm

Given an array of positive and negative numbers like [-2, 1, -3, 4, -1, 2, 1, -5, 4], which contiguous slice has the largest sum? Checking every start and end pair takes O(n²) time, but Kadane's algorithm solves it in a single O(n) pass with two variables.

Brute force over all subarrays vs extend-or-start-fresh

Kadane's algorithm finds the largest sum of a contiguous subarray in O(n) by keeping the best sum ending at each position and the best sum seen so far.

A subarray is a contiguous slice of an array. Brute force sums every slice in O(n²); Kadane's algorithm does it in one pass. The code below traces both on the same input.

Why does brute force repeat work? Look at what happens as we arrive at index i. Suppose we already know currentSum, the maximum sum of any subarray that ends at index i - 1. To form the best subarray that ends at index i, we only have two choices:

  1. Extend the previous run: append nums[i] to the best subarray ending at i - 1, giving currentSum + nums[i].
  2. Start fresh at i: abandon the previous run (because currentSum < 0 was dragging us down!) and start a new 1-element subarray [nums[i]], giving nums[i].

Kadane's algorithm on {-2, 1, -3, 4, -1, 2, 1, -5, 4}

Step 1 of 9

Array: -2, 1, -3, 4, -1, 2, 1, -5, 4. i at index 0.
current
-2
best
-2
Start with the first number: the current run is {-2}, so current and best are both -2.

Example 1 · Brute force: try every start and end (O(n²) time, O(1) space)

KadaneBruteDemo.javaJava
public class KadaneBruteDemo {    static int bruteForceMaxSubarray(int[] nums) {        int best = Integer.MIN_VALUE;        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;    }
    public static void main(String[] args) {        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};        System.out.println("Brute force : " + bruteForceMaxSubarray(nums));    }}
Output
Brute force : 6

What this code does

  • For every start index i, the inner loop extends the end index j and keeps the best running sum.
  • That checks all n(n + 1) / 2 slices, so the time is O(n²) with only a few variables of extra space.

Example 2 · Optimal: Kadane's one pass, traced step by step (O(n) time, O(1) space)

KadaneTraceDemo.javaJava
public class KadaneTraceDemo {    static int kadaneWithTrace(int[] nums) {        int currentSum = nums[0];        int bestSum = nums[0];        System.out.println("i=0 | x=" + nums[0] + " | currentSum=" + currentSum + " | bestSum=" + bestSum);        for (int i = 1; i < nums.length; i++) {            int x = nums[i];            String action = (x > currentSum + x) ? "start fresh" : "extend";            currentSum = Math.max(x, currentSum + x);            bestSum = Math.max(bestSum, currentSum);            System.out.println("i=" + i + " | x=" + x + " (" + action + ")"                + " | currentSum=" + currentSum + " | bestSum=" + bestSum);        }        return bestSum;    }
    public static void main(String[] args) {        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};        int ans = kadaneWithTrace(nums);        System.out.println("Kadane answer : " + ans);    }}
Output
i=0 | x=-2 | currentSum=-2 | bestSum=-2
i=1 | x=1 (start fresh) | currentSum=1 | bestSum=1
i=2 | x=-3 (extend) | currentSum=-2 | bestSum=1
i=3 | x=4 (start fresh) | currentSum=4 | bestSum=4
i=4 | x=-1 (extend) | currentSum=3 | bestSum=4
i=5 | x=2 (extend) | currentSum=5 | bestSum=5
i=6 | x=1 (extend) | currentSum=6 | bestSum=6
i=7 | x=-5 (extend) | currentSum=1 | bestSum=6
i=8 | x=4 (extend) | currentSum=5 | bestSum=6
Kadane answer : 6

What this code does

  • At i = 3 (x = 4), currentSum from i = 2 was -2, so starting fresh at 4 beats -2 + 4 = 2.
  • From i = 3 through i = 6 ([4, -1, 2, 1]), currentSum stays positive (4 -> 3 -> 5 -> 6), even across -1, because 3 is still a positive boost for the 2, 1 that follow.
  • It is faster than the brute force because the best slice ending at i is either the number alone or the best slice ending at i - 1 plus the number, so each number is handled once.

A subarray is a contiguous slice nums[i .. j] (0 <= i <= j < n). An array of length n has (n(n + 1))/2 non-empty subarrays. The brute-force approach loops over every start index i and extends j from i to n - 1, accumulating sum += nums[j] in O(n²) time.

That single decision — currentSum = Math.max(nums[i], currentSum + nums[i]) — is Kadane's algorithm. Tracking bestSum = Math.max(bestSum, currentSum) across i = 1 .. n - 1 finds the global maximum subarray sum in O(n) time and O(1) space.

  • If currentSum < 0, adding it to nums[i] makes the sum smaller than nums[i] alone, so we start fresh at nums[i].
  • If currentSum >= 0, carrying it forward helps (or ties), so we extend the run with currentSum + nums[i].
  • Hand trace on [-2, 1, -3, 4, -1, 2, 1, -5, 4]: currentSum takes values -2, 1, -2, 4, 3, 5, 6, 1, 5, and bestSum peaks at 6 (from [4, -1, 2, 1]).

All-negative arrays: why initialising to nums[0] matters

When the problem requires a non-empty subarray (length >= 1), what is the maximum subarray sum of [-8, -3, -6, -2, -5]? Every non-empty subarray has a negative sum, and the best one is the single largest element [-2] with sum -2.

Example 3 · Handling all-negative arrays cleanly without returning 0

AllNegativeKadaneDemo.javaJava
public class AllNegativeKadaneDemo {    static int kadane(int[] nums) {        int currentSum = nums[0];        int bestSum = nums[0];        for (int i = 1; i < nums.length; i++) {            currentSum = Math.max(nums[i], currentSum + nums[i]);            bestSum = Math.max(bestSum, currentSum);        }        return bestSum;    }
    public static void main(String[] args) {        System.out.println("[-8, -3, -6, -2, -5] -> " + kadane(new int[]{-8, -3, -6, -2, -5}));        System.out.println("[-10]                -> " + kadane(new int[]{-10}));        System.out.println("[-4, 0, -2]          -> " + kadane(new int[]{-4, 0, -2}));    }}
Output
[-8, -3, -6, -2, -5] -> -2
[-10]                -> -10
[-4, 0, -2]          -> 0

What this code does

  • On [-8, -3, -6, -2, -5], currentSum starts fresh at each negative number because adding a negative currentSum would only make it more negative.
  • bestSum records the least negative single element (-2), which is the true maximum non-empty subarray sum.
  1. Initialise long currentSum = nums[0]; and long bestSum = nums[0];.
  2. Loop for (int i = 1; i < nums.length; i++).
  3. Update currentSum = Math.max(nums[i], currentSum + nums[i]);.
  4. Update bestSum = Math.max(bestSum, currentSum);.

Many older tutorials write if (currentSum < 0) currentSum = 0; and initialise bestSum = 0. That version silently allows an empty subarray of sum 0 and returns 0 on [-8, -3, -6, -2, -5], which gets Wrong Answer on almost every coding platform! By initialising both currentSum = nums[0] and bestSum = nums[0] and looping from i = 1 with currentSum = Math.max(nums[i], currentSum + nums[i]), all-negative arrays are handled automatically without a single special if branch.

Predict the output

Predict the best sum

Read each loop and pick what it prints for an all-negative array.

Round 1 of 2

int[] nums = {-3, -1, -2};
int best = 0, cur = 0;
for (int x : nums) {
cur = Math.max(0, cur + x);
best = Math.max(best, cur);
}
System.out.println(best);

Returning the subarray itself (tracking start and end indices)

Sometimes you must return the best subarray itself, not just its sum. Three extra variables track where it starts and ends. The code below returns the indices.

At the end of the loop, Arrays.copyOfRange(nums, bestStart, bestEnd + 1) gives the exact maximum subarray.

Example 4 · Returning the actual maximum subarray using start and end pointers

KadaneSubarraySliceDemo.javaJava
import java.util.Arrays;
public class KadaneSubarraySliceDemo {    static int[] maxSubarraySlice(int[] nums) {        int currentSum = nums[0];        int bestSum = nums[0];        int tempStart = 0;        int bestStart = 0;        int bestEnd = 0;
        for (int i = 1; i < nums.length; i++) {            if (nums[i] > currentSum + nums[i]) {                currentSum = nums[i];                tempStart = i;            } else {                currentSum += nums[i];            }            if (currentSum > bestSum) {                bestSum = currentSum;                bestStart = tempStart;                bestEnd = i;            }        }        return Arrays.copyOfRange(nums, bestStart, bestEnd + 1);    }
    public static void main(String[] args) {        int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};        System.out.println("Slice of a : " + Arrays.toString(maxSubarraySlice(a)));
        int[] b = {-9, -4, -7};        System.out.println("Slice of b : " + Arrays.toString(maxSubarraySlice(b)));    }}
Output
Slice of a : [4, -1, 2, 1]
Slice of b : [-4]

What this code does

  • tempStart marks where the current candidate subarray began, but we only copy tempStart into bestStart when currentSum actually beats bestSum.
  • That way, if a late start-fresh candidate at the end of the array never surpasses bestSum, bestStart and bestEnd still point to the true winning slice [4, -1, 2, 1].

Sometimes an interviewer asks you to return the actual subarray (or its [bestStart, bestEnd] indices), not just its sum. You only need three extra integer variables:

  • tempStart: the start index of the current run. Whenever starting fresh beats extending (nums[i] > currentSum + nums[i], i.e., currentSum < 0), set tempStart = i.
  • bestStart and bestEnd: whenever currentSum > bestSum, copy bestStart = tempStart and bestEnd = i.
In Arrays.copyOfRange(nums, from, to), from is inclusive (bestStart) and to is exclusive (bestEnd + 1).

Next step

Check your understanding

10 quick questions