Medium Array Problems Java

Kadane's Algorithm: Maximum Subarray Sum in Java

Find the maximum sum of a non-empty continuous subarray.

  • TimeO(n)
  • SpaceO(1)
  • Hints3
  • Read2 min
Quick answer

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.

Dynamic programmingSingle passSubarray
1

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.

Input

An integer array arr with at least one element.

Output

The maximum sum, with the start and end index of the subarray.

Examples

Example 1
Inputarr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Outputsum 6, index 3 to 6

4 + (-1) + 2 + 1 = 6.

Example 2
Inputarr = [-8, -3, -6]
Outputsum -3, index 1 to 1

All 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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
A negative running sum can only make the next value smaller. Drop it and start again.
2 Hint 2
current = max(arr[i], current + arr[i])
3 Hint 3
Update best after every step, because the best part may end anywhere.
4

Approach

Reveal the step-by-step approach
  1. Set current and best to the first element.
  2. For each next element:
    • If current is negative, throw it away and restart from this element.
    • Otherwise add this element to current.
  3. If current is bigger than best, save it and save the two indexes.
  4. At the end, best is 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.

5

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.

6

Solution

Reveal the full Java solution
Solution.java
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.

TimeO(n)
SpaceO(1)
7

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

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us