Maximum subarray: Kadane's algorithm
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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:
- Extend the previous run: append
nums[i]to the best subarray ending ati - 1, givingcurrentSum + nums[i]. - Start fresh at
i: abandon the previous run (becausecurrentSum < 0was dragging us down!) and start a new 1-element subarray[nums[i]], givingnums[i].
Kadane's algorithm on {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Step 1 of 9
- current
- -2
- best
- -2
Example 1 · Brute force: try every start and end (O(n²) time, O(1) space)
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)); }}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)
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); }}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),currentSumfromi = 2was-2, so starting fresh at4beats-2 + 4 = 2. - From
i = 3throughi = 6([4, -1, 2, 1]),currentSumstays positive (4 -> 3 -> 5 -> 6), even across-1, because3is still a positive boost for the2, 1that 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 tonums[i]makes the sum smaller thannums[i]alone, so we start fresh atnums[i]. - If
currentSum >= 0, carrying it forward helps (or ties), so we extend the run withcurrentSum + nums[i]. - Hand trace on
[-2, 1, -3, 4, -1, 2, 1, -5, 4]:currentSumtakes values-2, 1, -2, 4, 3, 5, 6, 1, 5, andbestSumpeaks at6(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
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})); }}[-8, -3, -6, -2, -5] -> -2 [-10] -> -10 [-4, 0, -2] -> 0
What this code does
- On
[-8, -3, -6, -2, -5],currentSumstarts fresh at each negative number because adding a negativecurrentSumwould only make it more negative. bestSumrecords the least negative single element (-2), which is the true maximum non-empty subarray sum.
- Initialise
long currentSum = nums[0];andlong bestSum = nums[0];. - Loop
for (int i = 1; i < nums.length; i++). - Update
currentSum = Math.max(nums[i], currentSum + nums[i]);. - 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
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
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))); }}Slice of a : [4, -1, 2, 1] Slice of b : [-4]
What this code does
tempStartmarks where the current candidate subarray began, but we only copytempStartintobestStartwhencurrentSumactually beatsbestSum.- That way, if a late start-fresh candidate at the end of the array never surpasses
bestSum,bestStartandbestEndstill 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), settempStart = i.bestStartandbestEnd: whenevercurrentSum > bestSum, copybestStart = tempStartandbestEnd = i.
Arrays.copyOfRange(nums, from, to), from is inclusive (bestStart) and to is exclusive (bestEnd + 1).Next step
Check your understanding
10 quick questions