Maximum Sum Circular Subarray
Find the largest sum of neighbouring numbers in an array whose end joins its start.
You are given an array of integers nums
Example 1
Output: 3
Explanation: the run [3] on its own.
Example 2
Output: 10
Explanation: the run [5, 5], going past the end and on from the start.
Example 3
Output: -2
Explanation: the run [-2] on its own.
The Idea
Think of the numbers written around a circle, like the hours on a clock face. After 12 comes 1, and after the last number of the array comes the first. You pick a run of neighbours on that circle and add them up, and you want the run with the biggest total. It must hold at least one number, and it cannot go all the way round and use a number twice.
In Example 1, [1, -2, 3, -2][5, -3, 5]
So there are two kinds of run: runs that stay inside the array, and runs that wrap, going past the end and on from the start. How do we check every wrapping run without trying each start and each length one by one?
Look at the picture below. The arrow, labelled "the end joins the start", leads from index 2 back to index 0. The wrapping run keeps both 5s, and what it leaves out is the -3 in the middle, marked "left out: ā3".
That is true of every wrapping run: what it leaves out is a run in the middle of the array that does not wrap. The kept part and the left-out part together make up the whole array, so the kept sum is the sum of the whole array, its total, minus the left-out sum. The bottom line of the picture shows this: total 7 minus the left-out -3 gives 10.
So the best wrapping run is the total minus the smallest run in the middle. Both kinds now come down to a search on a plain array, without any wrapping: one search for the largest run sum, and one for the smallest.
Solution Approach
Turning these two searches into code means settling three things: how to find the best run that does not wrap, how to find the smallest run for the wrapping case, and what to do when every number is negative.
The best run that does not wrap
How do we find the largest run sum without trying every run? Trying every start with every length means about n² sums, where n is the length of the array. For 100,000 numbers, that is about 10 billion sums.
One pass from left to right is enough. Keep curMaxxxxx
In code that is curMax = Math.max(x, curMax + x)curMaxbestMax[5, -3, 5]curMaxbestMax
The smallest run, for the wrapping case
How do we find the run to leave out? With the same pass, using Math.minMath.maxcurMinxbestMin[5, -3, 5]curMinbestMin
The same loop also adds up totaltotal - bestMin
When every number is negative
Is total - bestMin
For [-3, -2, -3]bestMintotal - bestMinbestMaxbestMaxbestMaxbestMax
Java Solution
The method maxSubarraySumCircular
- First, set
and the two running sums,total andcurMax , to 0. StartcurMin atbestMax andInteger.MIN_VALUE atbestMin , so the first number replaces both.Integer.MAX_VALUE - Loop over every number
inx , and addnums tox .total - In the same loop, set
tocurMax , the best run ending atMath.max(x, curMax + x) , and keep the largest value so far inx .bestMax - Do the same with
forMath.min , the smallest run ending atcurMin , and keep the smallest value so far inx .bestMin - After the loop, if
is below 0, every number is negative, so returnbestMax .bestMax - Otherwise, return the larger of
andbestMax .total - bestMin
The main[-5, 1, -5][2, -1, 2, -1, 2]
public class MaximumSumCircularSubarray {
public static int maxSubarraySumCircular(int[] nums) {
int total = 0;
int curMax = 0;
int bestMax = Integer.MIN_VALUE; // best run that does not wrap
int curMin = 0;
int bestMin = Integer.MAX_VALUE; // smallest run: leaving it out gives a wrapping run
for (int x : nums) {
total += x;
curMax = Math.max(x, curMax + x); // extend the run or start again at x
bestMax = Math.max(bestMax, curMax);
curMin = Math.min(x, curMin + x);
bestMin = Math.min(bestMin, curMin);
}
if (bestMax < 0) {
return bestMax; // all negative: the wrapping run would be empty
}
return Math.max(bestMax, total - bestMin);
}
public static void main(String[] args) {
System.out.println(maxSubarraySumCircular(new int[] {1, -2, 3, -2}));
System.out.println(maxSubarraySumCircular(new int[] {5, -3, 5}));
System.out.println(maxSubarraySumCircular(new int[] {-3, -2, -3}));
System.out.println(maxSubarraySumCircular(new int[] {7}));
System.out.println(maxSubarraySumCircular(new int[] {-5, 1, -5}));
System.out.println(maxSubarraySumCircular(new int[] {2, -1, 2, -1, 2}));
}
}
Running it prints:
3
10
-2
7
1
5
Look at the second line: 10 is the wrapping run 5, 5 from the picture, found as 7 - (-3). On the third line, -2 for [-3, -2, -3]bestMax
The 1 on the fifth line comes from [-5, 1, -5]total - bestMinbestMaxMath.max
The last line, 5, wraps. In [2, -1, 2, -1, 2]
Complexity
The method reads each number once and keeps only a few running values.
- Time: O(n), because the single loop visits each of the n numbers once and does a few additions and comparisons there, and the wrapping case needs no second pass.
- Space: O(1). Five
variables hold the whole state, however longint is. The array is never copied or doubled to imitate the wrap.nums
Turning "keep the two ends" into "leave out a middle part" also solves