Scrivio Interview library
Dynamic programmingDynamic programmingReported 92 times · 16 min read · updated 15 November 2026

Find the contiguous subarray with the largest sum.

1What the question asks, told as a shopkeeper's notebook

Imagine a small shop that writes down each evening how much it made or lost that day. One week the notebook reads 3, -4, 5, -1, 2, -6, 4, in thousands. The owner asks which stretch of consecutive days made the most money in total: not the single best day, and not a hand-picked set of good days, but one unbroken stretch, such as Wednesday to Friday. That is our problem, with the notebook as an array of integers.

The question calls such a stretch a contiguous subarray. Contiguous means touching, with no gaps, so [5, -1, 2], at indexes 2 to 4, is one, but [3, 5] is not, because it skips the -4 between them. We will mostly call it a run, which is shorter, and write the run from index 2 to index 4 as a[2..4]. We want the run whose numbers add up to the most.

This looks like a lot of work, because even seven days have 28 different runs. We will honestly try them all first, and then discover that one walk from left to right, holding two numbers in our head, is enough. The problem is smaller than it looks.

Let us work a few runs out by hand. [3] gives 3, [3, -4] gives -1, and [3, -4, 5] gives 4. Starting later, [5] gives 5, [5, -1] gives 4, and [5, -1, 2] gives 6. Going on, [5, -1, 2, -6] falls to 0, and adding the last day gives only 4. Nothing beats 6, so the answer is 6, from index 2 to 4. Notice that the best run contains a losing day; the days around it more than make up for it.

PictureSeven days of profit and loss

Each cell is one day's result. The highlighted run of neighbouring days has the largest total.

  1. 30-4152-1324-6546fromto
    best sum
    6
    run
    a[2..4]

    1The best run is days 2 to 4: 5 + (-1) + 2 = 6. It even contains a losing day, because the days around it make up for the loss.

What to assume

Can the array be empty?
We assume it has at least one element.
Must the run contain at least one day?
Yes, so for [-3, -1, -2] the answer is -1, the least bad day, not 0.
Should we say where the run is?
We return its bounds as well as its sum.

A careful candidate asks a few questions first. Can the array be empty? We assume it has at least one element. Must the run contain at least one day? Yes, so for [-3, -1, -2] the answer is -1, the least bad day, not 0. Should we say where the run is? We will return its bounds as well as its sum.

2How to recognise that this is dynamic programming

A beginner reading this question often reaches for a shortcut. Sorting the array and taking the biggest numbers moves the days around, so they are no longer neighbours. Adding up all the positive numbers, 3 + 5 + 2 + 4 = 14, picks days that are not next to each other either. The word contiguous rules out both, and trying every run is correct but slow. So the real question is how to find the best run without trying them all.

The first clue is the word largest. We want the best of very many candidates, and best-of-many questions are where dynamic programming often lives, because it stops us working out the same candidates again and again.

The second clue is the word contiguous, and it is the more useful one. Every run ends at some index. Among the runs that end at index i, one is a[i] on its own, and every other one is a run ending at i - 1 with a[i] added at the end. So the runs at one position grow directly out of the runs at the position before it.

So the pattern is dynamic programming, a name that hides a simple idea. It means breaking a problem into smaller questions of the same kind, called subproblems, answering each one once, writing the answer down, and building bigger answers from smaller ones. Our small question will be the best sum of a run that ends exactly at index i. There is one per index, so this is one dimensional dynamic programming, and the solution we will reach is Kadane's algorithm. The rule to carry to new problems is this: if the best answer ending at i can be built from the best answer ending at i - 1, write that relation down and walk the array once.

Two other patterns look similar. A sliding window, a range whose two ends only move right, must know when to give up its left end, but with negative numbers the sum can fall and then rise again, so it cannot tell. Prefix sums, the running totals from the start, lead to the same idea in different clothes, and divide and conquer takes O(n log n) time, which is slower.

3The honest first attempt, trying every run

The honest first attempt is to look at every run, add it up and keep the best sum. That is a good start, because it is clearly correct and it will show us where work is wasted. A run is fixed by its start index i and its end index j, so we try every start, and for each start we move the end to the right one day at a time.

One small improvement comes for free. The run ending at j is the run ending at j - 1 plus one number, so for each start we keep a running sum and add a[j] as j moves, instead of adding up every run from scratch, which would cost O(n cubed).

Before the code, let us watch three of its starting points, 0, 1 and 2, at the moment each one reaches index 4. The panel counts every addition made so far.

Step throughThe brute force adds the same numbers again and again

Three runs that all end at index 4. Cells added again for a later start are marked as compared.

  1. 30-4152-1324-6546ij
    start i
    0
    end j
    4
    sum
    5
    additions
    5

    1Start 0 reaches index 4 by adding 3, -4, 5, -1 and 2, one at a time. The run a[0..4] sums to 5.

  2. 30-4152-1324-6546ij
    start i
    1
    end j
    4
    sum
    2
    additions
    11

    2Start 0 went on to index 6, seven additions in all. Then start 1 adds -4, 5, -1 and 2 all over again to reach index 4, four additions already made once. The run sums to 2.

  3. 30-4152-1324-6546ij
    start i
    2
    end j
    4
    sum
    6
    additions
    16

    3Start 2 adds 5, -1 and 2 for a third time. Its run a[2..4] sums to 6, the best run that ends at index 4, but we paid for these numbers three times.

Java
static int maxSubarrayBrute(int[] a) {
int best = a[0];
for (int i = 0; i < a.length; i++) { // every possible start
int sum = 0;
for (int j = i; j < a.length; j++) { // every end at or after it
sum += a[j]; // sum of a[i..j], one addition
best = Math.max(best, sum);
}
}
return best;
}

The code is the same idea written out. The outer loop chooses the start, the inner loop moves the end, sum += a[j] extends the run by one day, and best keeps the largest sum seen.

Now let us count on our seven days. Start 0 has 7 runs, start 1 has 6, and so on down to 1, so 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 additions. For n elements that is n(n + 1) / 2, about half of n times n, which we write as O(n squared): doubling the array makes the work about four times larger. The extra space is O(1), only a few variables.

Now look back at the picture. All three runs end at index 4, and the numbers 5, -1 and 2 were added three times. Yet to know the best run ending at index 4, we needed only one fact: the best run ending at index 3, which is [5, -1] with sum 4. Adding 2 gives 6. The brute force never keeps such facts; it throws its running sum away at every new start.

So the question to ask is whether, when we arrive at index i, we could already know the best run ending at i - 1 and simply build on it.

4From the waste to Kadane's idea, one step at a time

Let us give that fact a name. endingHere(i) is the largest sum of a run that ends exactly at index i, which means the run must include a[i], with as many neighbours to its left as we like. It is not the final answer; it is the smaller question, one per index.

Let us work out the first few by hand. At index 0 the only run is [3], so endingHere(0) = 3. At index 1 the runs [-4] and [3, -4] sum to -4 and -1, so endingHere(1) = -1. At index 2 the runs [5], [-4, 5] and [3, -4, 5] sum to 5, 1 and 4, so endingHere(2) = 5. Now let us look for a shortcut.

Every run ending at index i is either a[i] alone or a run ending at i - 1 with a[i] added. If we extend, we should extend the best of those, whose sum is endingHere(i - 1). So endingHere(i) = max(a[i], endingHere(i - 1) + a[i]), where max means the larger of the two. Check it at index 2: max(5, -1 + 5) = 5, as we found by hand, but now with one addition and one comparison.

A beginner often asks a fair question here. Why is extending only the best run ending at i - 1 enough? Could a worse run overtake it once a[i] is added? It cannot, because the same a[i] is added to every candidate. If one stretch earned more than another up to yesterday, then after adding today's result to both, it still earns more.

The rule also has a plain meaning, and here our shopkeeper returns. The max chooses between carrying the best stretch so far into today and starting a new stretch today. Carrying it is worse exactly when that stretch is negative: a debt carried into today only makes today's total smaller, so we drop it and start again. If it is zero or positive, we keep it. That is all Kadane's algorithm does.

Every run ends somewhere, so the overall answer is the largest endingHere. Here is that middle step as code, with an array called dp, the usual name for a table of subproblem answers.

Java
static int maxSubarrayTable(int[] a) {
int[] dp = new int[a.length]; // dp[i]: best sum of a run that ends exactly at i
dp[0] = a[0];
int best = dp[0];
for (int i = 1; i < a.length; i++) {
dp[i] = Math.max(a[i], dp[i - 1] + a[i]); // start fresh, or extend the best run ending at i - 1
best = Math.max(best, dp[i]);
}
return best;
}

dp[0] is a[0], because the only run ending at index 0 is a[0] itself. Each later dp[i] uses the rule, and best keeps the largest entry. On our example the table fills in as [3, -1, 5, 4, 6, 0, 4], and its largest entry is 6.

Now look closely at the loop. To fill dp[i], it reads only dp[i - 1]; every older entry is written once and never read again. So one variable holding the latest value is enough, and replacing the table with it is the last step to Kadane's algorithm. It brings the extra memory down from O(n) to O(1).

To report where the run is, we add a variable start, the index where the current run began. When we start fresh at i, start becomes i, and whenever the running value beats best, we copy start and i into the best bounds.

5Watching the running total walk across the seven days

The picture follows the final program on our seven days. Under the cells, i marks the day we are on and start marks where the current run began. Dropped days are dimmed, days already in the run are marked as compared, and the panel shows the decision, run (our endingHere), and the best so far.

Watch run most closely. In each frame it either grows by a[i] or, when it was negative, is replaced by a[i].

Step throughKadane's walk across [3, -4, 5, -1, 2, -6, 4]

i is the day we are on, start is where the current run began. Dimmed days were dropped, and the run so far is marked as compared.

  1. 30-4152-1324-6546istart
    a[i]
    3
    decision
    take a[0] alone
    run
    3
    best
    3
    best run
    a[0..0]

    1We start with the first day alone. The run ending at index 0 is just 3, so run = 3 and best = 3, from index 0 to 0.

  2. 30-4152-1324-6546istart
    a[i]
    -4
    decision
    extend the run
    run
    -1
    best
    3
    best run
    a[0..0]

    2At index 1 the run before it was 3, which is not negative, so we extend: 3 + (-4) = -1. That is not better than 3, so best stays 3.

  3. 30-4152-1324-6546istart
    a[i]
    5
    decision
    start fresh at 2
    run
    5
    best
    5
    best run
    a[2..2]

    3At index 2 the run before it is -1, a debt. Carrying it would only lower 5, so we drop days 0 and 1 and start fresh: run = 5, and best becomes 5.

  4. 30-4152-1324-6546istart
    a[i]
    -1
    decision
    extend the run
    run
    4
    best
    5
    best run
    a[2..2]

    4At index 3 the run before it is 5, so we extend: 5 + (-1) = 4. A small loss, but the run is still worth keeping. best stays 5.

  5. 30-4152-1324-6546istart
    a[i]
    2
    decision
    extend the run
    run
    6
    best
    6
    best run
    a[2..4]

    5At index 4 we extend again: 4 + 2 = 6. This beats 5, so best becomes 6, and we record the run from start 2 to index 4.

  6. 30-4152-1324-6546istart
    a[i]
    -6
    decision
    extend the run
    run
    0
    best
    6
    best run
    a[2..4]

    6At index 5 we extend: 6 + (-6) = 0. The run has fallen to 0, but best keeps the 6 we already found.

  7. 30-4152-1324-6546istart
    a[i]
    4
    decision
    extend the run
    run
    4
    best
    6
    best run
    a[2..4]

    7At index 6 the run before it is 0, which is not negative, so we extend: 0 + 4 = 4. Starting fresh would also give 4. It does not beat 6.

  8. 30-4152-1324-6546fromto
    best
    6
    best run
    a[2..4]

    8The loop has finished. The best run we recorded is a[2..4], the days 5, -1 and 2, with sum 6, and that is the answer.

At index 1 the run falls from 3 to -1, yet we still extend, because the decision looks at the value before this day, 3, which was not negative. Many beginners expect the run to be dropped here.

At index 2 comes the decision that finds the answer. The run we would carry in is -1, a debt, so we drop days 0 and 1 and start fresh at 5, with start set to 2. The run then goes to 4, and to 6 at index 4, so best becomes 6 with bounds 2 to 4.

At index 5 the -6 pulls the run down to 0, but best keeps its 6. At index 6 the carried value 0 is not negative, so we extend to 4; starting fresh would also give 4, and the program only starts fresh below zero. It does not beat 6, so the answer stays 6, from index 2 to 4.

6The complete Java program

Here is the full program. The method returns a small record with the best sum and the bounds of the best run, and show prints the sum and the run. main tries our example, an all-negative array, and an array whose best run is the whole array.

Java
import java.util.Arrays;
public class MaxSubarray {
record Result(int sum, int from, int to) {}
// Kadane's algorithm: best sum of a non-empty contiguous subarray, with its bounds.
static Result maxSubarray(int[] a) {
int bestEndingHere = a[0], start = 0; // best subarray that ends at the current index
int best = a[0], bestFrom = 0, bestTo = 0;
for (int i = 1; i < a.length; i++) {
if (bestEndingHere < 0) { // a negative prefix only hurts: start fresh at i
bestEndingHere = a[i];
start = i;
} else { // otherwise extend the run to include a[i]
bestEndingHere += a[i];
}
if (bestEndingHere > best) {
best = bestEndingHere;
bestFrom = start;
bestTo = i;
}
}
return new Result(best, bestFrom, bestTo);
}
static void show(int[] a) {
Result r = maxSubarray(a);
int[] part = Arrays.copyOfRange(a, r.from(), r.to() + 1);
System.out.println(r.sum() + " " + Arrays.toString(part));
}
public static void main(String[] args) {
show(new int[] {3, -4, 5, -1, 2, -6, 4}); // 6 [5, -1, 2]
show(new int[] {-3, -1, -2}); // -1 [-1]
show(new int[] {5, 4, -1, 7, 8}); // 23 [5, 4, -1, 7, 8]
}
}

Let us read maxSubarray in the order it runs. The first two lines set everything from a[0]: the running value bestEndingHere, which is the program's name for endingHere, the start of the current run at 0, best, and the best bounds 0 to 0. That is the answer for the first day alone, so the loop starts at i = 1.

Inside the loop comes the shopkeeper's rule. If bestEndingHere is negative, carrying it would only hurt, so we replace it with a[i] and set start to i. Otherwise we extend the run by adding a[i]. Notice that we test the value before today's number is added; that is endingHere(i - 1) from our rule.

Then, if bestEndingHere beats best, we record its sum, its start and today's index. The test is strictly greater than, so of two equal runs we keep the first. After the loop, best and its bounds go back in a Result.

show cuts the run out with Arrays.copyOfRange(a, from, to + 1), adding 1 because copyOfRange stops just before its last index. So main prints 6 [5, -1, 2], then -1 [-1], then 23 with the whole array.

The most common beginner mistake is to start best at 0, or to reset the run to 0 instead of to a[i]. It is tempting, because it works on most inputs, but for [-3, -1, -2] it reports 0, the sum of an empty run, which the question does not allow.

7How much it costs, and the cases at the edges

On our example the loop ran six times, for indexes 1 to 6, with the same few operations each time, against 28 additions for the brute force. For n elements it runs n - 1 times, so the time is O(n). We cannot do better, because any day we skipped might hold a huge number.

The memory is a handful of int variables whatever the length of the array, so the extra space is O(1).

Comparing the approaches
ApproachTimeExtra space
Every run, added up from scratchO(n^3)O(1)
Every start, with a running sum (brute force)O(n^2)O(1)
Divide and conquerO(n log n)O(log n) recursion
Dynamic programming with a dp tableO(n)O(n)
Kadane's algorithm, one running valueO(n)O(1)

When every number is negative, as in [-3, -1, -2], the run starts at -3. At index 1 it is negative, so we start fresh at -1, which becomes best. At index 2, -1 is negative, so we start fresh at -2, which does not beat -1. The answer is -1, and it is right only because we began from a[0].

A single element never enters the loop and comes back with bounds 0 to 0. An empty array would make a[0] throw an ArrayIndexOutOfBoundsException, so we either state that the input has at least one element, as we assumed, or check for it first. And if a sum could pass about two billion, the int would overflow, so we would switch to long.

8Follow-up questions

What if an empty run is allowed, so the answer can be 0?

Then a run of no days counts, with sum 0. We start both the running value and best at 0 instead of a[0], loop from index 0, and reset the running value to 0 whenever it goes negative. For an all-negative array the answer becomes 0. The two versions differ only when every number is negative, so it is worth asking which one the interviewer means.

How would you find the largest sum in a circular array, where a run may wrap from the end back to the start?

Picture the week written around a clock face. A run that wraps past the end leaves out one unbroken stretch in the middle, so its sum is the total minus that stretch, which is largest when the left-out stretch is smallest. So we run Kadane twice, once for the largest run and once with min for the smallest, and take the larger of the plain maximum and the total minus the minimum. If every number is negative, that would mean taking nothing, so we return the plain maximum.

How is the maximum product subarray different?

Multiplying by a negative number turns the smallest product into the largest, so one running value is not enough. We carry two: the largest and the smallest product of a run ending at i. At each element the new largest is the biggest of a[i], the old largest times a[i] and the old smallest times a[i], and the new smallest is found the same way with min. It is still one pass.

9Conclusion

Trying every start and end takes O(n squared), because it keeps rebuilding the best run ending at each index. Making that the small question gives Kadane's rule: the best run ending at i is the larger of a[i] alone and a[i] added to the best run ending at i - 1, or in plain words, a carried debt only hurts, so drop it. One pass gives O(n) time and O(1) space. The clue to remember is that the best answer ending at one position is built from the best answer ending at the position before.

What to say in the interviewAbout 70 seconds aloud

Open with

First I would confirm that the subarray is contiguous and non-empty, so an all-negative array returns its largest element. The brute force tries every start and extends a running sum to every end, which is O(n squared), and it keeps rebuilding the best sum ending at each index.

Then, if they want more

So I make that the subproblem, which is dynamic programming: the best sum of a run ending exactly at i is either a[i] alone or a[i] plus the best sum ending at i minus one, and extending is worse only when that previous best is negative. That is Kadane's algorithm.

I walk the array once with a running value that starts at a[0]. If it is negative I start fresh at the current element and remember its index; otherwise I add the element. If it beats the best, I record it with its bounds. Each step needs only the previous value, so it is O(n) time and O(1) space. Starting from a[0] rather than zero keeps all-negative input correct.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 92 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the contiguous subarray with the largest sum.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-contiguous-subarray-with-the-largest-sum-3bc718/

More dynamic programming questions