Kadane's Algorithm: Maximum Subarray Sum in Java
Find the maximum sum of a non-empty continuous subarray.
- Time
O(n) - Space
O(1) - Hints3
- Read2 min
Kadane's algorithm finds the maximum subarray sum in one pass. At each element, choose the bigger of two values: the element alone, or the element added to the running sum. Keep the best running sum you have seen. It takes O(n) time and O(1) extra space.
Problem statement
You get an array of integers. Find the largest sum of a continuous part of it (a subarray) with at least one element. Solve it with Kadane's algorithm.
In [-2, 1, -3, 4, -1, 2, 1, -5, 4] the best part is [4, -1, 2, 1], with sum 6.
An integer array arr with at least one element.
The maximum sum, with the start and end index of the subarray.
Examples
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]sum 6, index 3 to 64 + (-1) + 2 + 1 = 6.
arr = [-8, -3, -6]sum -3, index 1 to 1All values are negative, so the best part is the single value -3.
Constraints
- 1 <= n <= 10^5
- Values fit in a 32-bit int and may be negative
Think before you code
Reveal the questions to ask yourself first
- If the sum so far is negative, does it help the next element?
- What is the best subarray that ends exactly at index i?
- Why must the answer start from arr[0] and not from 0?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Set
currentandbestto the first element. - For each next element:
- If
currentis negative, throw it away and restart from this element. - Otherwise add this element to
current.
- If
- If
currentis bigger thanbest, save it and save the two indexes. - At the end,
bestis the answer.
The simple method tries every start and end, which takes O(n^2) time. Kadane's algorithm for maximum subarray sum needs one pass because the best sum ending here depends only on the best sum ending one step before. That is a small piece of dynamic programming. See more in data structures and algorithms.
Dry run
Walk through the example step by step
Kadane's algorithm visualization for [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
index | value | current | what happened | best
------+-------+---------+---------------+-----
0 | -2 | -2 | start | -2
1 | 1 | 1 | restart | 1
2 | -3 | -2 | add | 1
3 | 4 | 4 | restart | 4
4 | -1 | 3 | add | 4
5 | 2 | 5 | add | 5
6 | 1 | 6 | add | 6
7 | -5 | 1 | add | 6
8 | 4 | 5 | add | 6
The last restart before the best sum was at index 3, so the part is index 3 to 6.
Solution
Reveal the full Java solution
public class Kadane {
// Returns {maxSum, startIndex, endIndex}. arr must not be empty.
public static long[] maxSubarray(int[] arr) {
long current = arr[0];
long best = arr[0];
int start = 0, bestStart = 0, bestEnd = 0;
for (int i = 1; i < arr.length; i++) {
if (current < 0) {
current = arr[i]; // a negative sum only hurts: restart
start = i;
} else {
current += arr[i];
}
if (current > best) {
best = current;
bestStart = start;
bestEnd = i;
}
}
return new long[]{best, bestStart, bestEnd};
}
public static void main(String[] args) {
int[][] tests = {
{-2, 1, -3, 4, -1, 2, 1, -5, 4},
{-8, -3, -6}
};
for (int[] t : tests) {
long[] r = maxSubarray(t);
System.out.println("sum " + r[0] + ", index " + r[1] + " to " + r[2]);
}
// sum 6, index 3 to 6
// sum -3, index 1 to 1
}
}current is the best sum that ends at this index. best is the best sum anywhere so
far. The code uses long so that large values do not overflow.
Kadane's algorithm in Java code, short form
If you only need the sum and it fits in an int, this is enough:
static int maxSum(int[] arr) {
int current = arr[0];
int best = arr[0];
for (int i = 1; i < arr.length; i++) {
current = Math.max(arr[i], current + arr[i]);
best = Math.max(best, current);
}
return best;
}
Both versions of Kadane's algorithm in Java give the same sum. The main solution also tells you where the subarray is, which makes a good follow-up question.
Why 0 is the wrong starting value
With best = 0, the array [-8, -3, -6] would return 0. No part of the array has that
sum. Starting from arr[0] fixes it. Some questions allow an empty subarray. Only
then is 0 correct.
Practise next
Solve two sum, try the missing number problem, and revise the Java coding questions. If you want to learn with a trainer, see the Java full stack course.
O(n)O(1)Review before the interview
Common mistakes
- Starting best at 0, which gives a wrong answer when all values are negative.
- Mixing up subarray and subsequence. A subarray must be continuous.
- Saving the start index on every step instead of only on a restart.
Edge cases to test
- One element: the answer is that element.
- All negative: the answer is the largest single value.
- All positive: the answer is the whole array.
Interview follow-ups
- How would you find the maximum sum in a circular array?
- How would you find the maximum product of a subarray?
- How would you find the maximum sum if you may delete one element?
Keep practising
Find the Sum of All Elements in an Array
Hints · Dry run · SolutionSolve Similar problemFind the Largest Element in an Array
Hints · Dry run · SolutionSolve Similar problemFind a Pair With a Given Sum in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
