Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write a Java method that returns the maximum sum of a contiguous subarray and the start and end index of that subarray. The input can contain only negative numbers and up to 10 million elements with values up to 1 billion.

We use Kadane's algorithm: walking left to right, we keep the best sum of a subarray that ends at the current index, current = max(nums[i], current + nums[i]), and the best sum seen anywhere. When current restarts at nums[i] we remember i as a candidate start, and when best improves we record that start and i as the answer. We initialize with nums[0], not 0, so an array of only negative numbers returns its largest element, and we keep the sums in long, because 10 million values of up to 1 billion can reach 10^16, far beyond int. The method is O(n) time and O(1) space.

Background to this question

Maximum subarray is a classic dynamic programming problem, and it appears in practice when we look for the best stretch in a time series: the most profitable run of days, the longest high-traffic window, or the strongest signal in sensor data. This version of the question adds three details that catch people out: returning the indexes, not just the sum, inputs that are all negative, and values large enough to overflow int. In this answer, we will recap the brute force and the key idea, write Kadane's algorithm with indexes, trace it, look at the all-negative and overflow cases, and then mention divide and conquer and the circular follow-up.

1A Quick Recap of the Problem

A contiguous subarray is a run of neighbouring elements, such as nums[3] to nums[6]. We want the run with the largest sum. For [-2, 1, -3, 4, -1, 2, 1, -5, 4], the answer is 4 + (-1) + 2 + 1 = 6, from index 3 to index 6. The subarray must contain at least one element, which matters for all-negative input.

The brute force tries every start and every end and keeps a running sum, which is O(n^2). For 10 million elements that is about 5 x 10^13 additions, many hours of work. We need a single pass.

2The Idea Behind Kadane's Algorithm

Think about the best subarray that ends exactly at index i. It either is nums[i] on its own, or it is the best subarray ending at i - 1 with nums[i] added. If the best sum ending at i - 1 is negative, carrying it along can only make things worse, so we start fresh at i. That gives the rule current = max(nums[i], current + nums[i]). The best subarray overall ends somewhere, so the answer is the largest current we ever see.

To return indexes, we track where the current run started. When we start fresh, the new run starts at i. When current beats the best so far, the best subarray is the current run, from its start to i.

Java
record MaxSub(long sum, int start, int end) {}
static MaxSub maxSubarray(int[] nums) {
if (nums.length == 0) throw new IllegalArgumentException("empty input");
long current = nums[0], best = nums[0]; // start from the first element, not 0
int runStart = 0, bestStart = 0, bestEnd = 0;
for (int i = 1; i < nums.length; i++) {
if (current + nums[i] < nums[i]) { // the old run only drags us down
current = nums[i];
runStart = i; // a new run starts here
} else {
current += nums[i]; // extend the run
}
if (current > best) {
best = current;
bestStart = runStart;
bestEnd = i;
}
}
return new MaxSub(best, bestStart, bestEnd);
}
maxSubarray(new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}); // MaxSub[sum=6, start=3, end=6]
maxSubarray(new int[] {-3, -1, -2}); // MaxSub[sum=-1, start=1, end=1]
Tracing the example
inums[i]current (run start)best (start..end)
0-2-2 (0)-2 (0..0)
111 (1), restart1 (1..1)
2-3-2 (1)1 (1..1)
344 (3), restart4 (3..3)
4-13 (3)4 (3..3)
525 (3)5 (3..5)
616 (3)6 (3..6)
7-51 (3)6 (3..6)
845 (3)6 (3..6)

Notice that the condition current + nums[i] < nums[i] is the same as current < 0. We write the restart explicitly so we know exactly when to move runStart. With a strict greater-than when updating best, ties keep the earliest subarray, which is a choice we can mention.

3All-Negative Input and the Zero Trap

A popular shortcut initializes best and current to 0 and resets current to 0 whenever it goes negative. For [-3, -1, -2] that version returns 0, the sum of an empty subarray, with no valid indexes. Since the question says the input can contain only negative numbers and the subarray must be non-empty, the right answer is -1 at index 1. Starting from nums[0] and letting current stay negative fixes it, because the restart rule then picks the largest single element.

4Why the Sums Must Be long

The input has up to 10 million elements with values up to 1 billion. The maximum possible sum is 10^7 x 10^9 = 10^16. An int holds at most 2,147,483,647, about 2.1 x 10^9, so an int sum overflows after just three elements of 1 billion: 3 x 10^9 wraps around to -1,294,967,296. The algorithm would then restart there and return a wrong range without any error. A long holds up to about 9.2 x 10^18, so 10^16 fits with plenty of room.

Reading the input is still an int[]: 10 million ints take 40 MB. Only the running sums need to be long. If we wanted an explicit guard anyway, Math.addExact throws ArithmeticException on overflow instead of wrapping.

5Complexity and the Divide and Conquer Alternative

Kadane's algorithm visits each element once with constant work, so it is O(n) time, and it keeps a handful of variables, so it is O(1) extra space. For 10 million elements that is a few milliseconds of work.

There is also a divide and conquer solution: split the array in half, solve each half, and compute the best subarray that crosses the middle by extending left and right from it. Combining is O(n) per level and there are log n levels, so it is O(n log n). It is worth mentioning because it shows the problem's structure and parallelizes naturally, but for a single machine Kadane's linear scan is simpler and faster.

6Follow-up questions

How would you handle a circular array?

In a circular array a subarray may wrap from the end to the start. The best wrapping subarray is the total sum minus the minimum subarray in the middle, and the minimum subarray is Kadane's algorithm with min instead of max. So the answer is the larger of the normal maximum and total minus the minimum. The exception is an all-negative array, where total minus minimum would be the empty subarray with sum 0; in that case we return the normal maximum, which is the largest element.

What does your method return for an empty array?

There is no non-empty subarray, so there is no meaningful answer. I throw IllegalArgumentException, as in the code, or return Optional.empty() if callers expect empty input. Returning 0 with indexes -1 is also possible, but then I would document it, because 0 looks like a real sum.

Is Kadane's algorithm dynamic programming?

Yes. The subproblem is the best sum of a subarray ending at index i, and each answer depends only on the previous one, so we keep a single variable instead of a whole table. That is why the space is O(1).

7Conclusion

In this answer, we saw that Kadane's algorithm keeps the best sum ending at each index, restarting when the previous run is negative, and the best sum overall. Recording the start whenever the run restarts and the end whenever the best improves gives us the indexes. Initializing with nums[0] makes all-negative arrays return their largest element instead of 0, and keeping the sums in long avoids silent overflow, since 10 million values of 1 billion can reach 10^16. The method is O(n) time and O(1) space, with divide and conquer as an O(n log n) alternative and total minus minimum for the circular case.

What to say in the interviewAbout 100 seconds aloud

Open with

I would use Kadane's algorithm. I walk the array once and keep two values: current, the best sum of a subarray that ends at the current index, and best, the largest sum seen so far.

Then, if they want more

For each element, current becomes the larger of the element alone and current plus the element. In other words, if the run so far is negative, I drop it and start a new run here.

To return indexes, I remember the start of the current run whenever I restart, and whenever current beats best I record that start and the current index as the answer. For the classic example that gives 6, from index 3 to 6. Two details matter for this input.

First, I initialise with the first element rather than zero, so an array of only negative numbers returns its largest element, for example minus one at index one, instead of zero for an empty subarray. Second, I keep the sums in a long.

Ten million values of up to a billion can add up to ten to the sixteenth, and an int overflows after just three of them, silently, which would make the algorithm restart in the wrong place. A long holds that easily. It is O(n) time and O(1) space.

I would mention the divide and conquer version, which is O(n log n), only as an alternative. For a circular array, I would take the larger of the normal answer and the total minus the minimum subarray, unless everything is negative.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Java method that returns the maximum sum of a contiguous subarray and the start...": https://scrivio-interview-library.netlify.app/java/coding-problems/64c05aef7c/