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 that is circular: after the last number comes the first one again. Return the largest sum of a non-empty subarray, which is a run of numbers that sit next to each other. A run may go past the end and carry on at the start, but it may use each number at most once.

Example 1
Input: nums = [1, -2, 3, -2]
Output: 3
Explanation: the run [3] on its own.
Example 2
Input: nums = [5, -3, 5]
Output: 10
Explanation: the run [5, 5], going past the end and on from the start.
Example 3
Input: nums = [-3, -2, -3]
Output: -2
Explanation: the run [-2] on its own.
Solution

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], the best run is the 3 on its own. Going past the end does not help there: the last -2 followed by the first 1 adds up to -1. Example 2 is different. In [5, -3, 5], the run from start to end sums to 7. But on the circle, the last 5 sits right next to the first 5, so the two make a run of their own, and 5 + 5 = 10.

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".

The array 5, -3, 5 with its end joined to its start. The wrapping run keeps both 5s and leaves out -3 in the middle: 5 + 5 = 10, which is the total 7 minus the 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 curMax, the best sum of a run that ends at the current number x. There are only two choices: add x to the best run that ended just before it, or start a new run at x. If the earlier run has a negative sum, it only pulls x down, so a new run is better.

In code that is curMax = Math.max(x, curMax + x), and the largest curMax seen on the way, bestMax, is the best run of all. For [5, -3, 5], curMax goes 5, 2, 7, so bestMax is 7. This one-pass method is called Kadane's algorithm, and Maximum Subarray explains it step by step.

The smallest run, for the wrapping case

How do we find the run to leave out? With the same pass, using Math.min in place of Math.max. curMin is the smallest sum of a run that ends at x, and bestMin is the smallest seen so far. For [5, -3, 5], curMin goes 5, -3, 2, so bestMin is -3.

The same loop also adds up total, so the best wrapping sum, total - bestMin, needs no extra pass: 7 - (-3) = 10. If the smallest run happens to sit at the start or the end, the kept part does not really wrap. It is still a run of neighbours, though, so the answer stays correct.

When every number is negative

Is total - bestMin always the sum of a real run? Not when the smallest run is the whole array. Then nothing is kept, and the result is 0, the sum of an empty run, which the problem does not allow.

For [-3, -2, -3], bestMin is -8, the total is also -8, and total - bestMin is 0, more than the true answer -2. That happens whenever every number is negative, and then bestMax is negative too. So when bestMax is below 0, the answer is bestMax itself, the largest single number. When some number is 0 or more, bestMax is at least 0, and the empty 0 can never beat it.

Java Solution

The method maxSubarraySumCircular works in these steps:

  1. First, set total and the two running sums, curMax and curMin, to 0. Start bestMax at Integer.MIN_VALUE and bestMin at Integer.MAX_VALUE, so the first number replaces both.
  2. Loop over every number x in nums, and add x to total.
  3. In the same loop, set curMax to Math.max(x, curMax + x), the best run ending at x, and keep the largest value so far in bestMax.
  4. Do the same with Math.min for curMin, the smallest run ending at x, and keep the smallest value so far in bestMin.
  5. After the loop, if bestMax is below 0, every number is negative, so return bestMax.
  6. Otherwise, return the larger of bestMax and total - bestMin.

The main method runs the three examples, a single number, [-5, 1, -5], whose smallest run is the whole array even though one number is positive, and [2, -1, 2, -1, 2], whose best run wraps.

Java
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:

Output
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] comes from the check on bestMax. A version of the method without that check prints 0 here, the sum of an empty run. The single number 7 on the fourth line is its own answer.

The 1 on the fifth line comes from [-5, 1, -5]. Here too the smallest run is the whole array, -9, so total - bestMin is 0. But bestMax is 1, so the check does not fire, and Math.max picks 1 over the empty 0.

The last line, 5, wraps. In [2, -1, 2, -1, 2] the whole array sums to 4, and that is also the best run that does not wrap. Leaving out the -1 at index 1 keeps 2, -1, 2 and then the first 2 again, which sum to 5.

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 int variables hold the whole state, however long nums is. The array is never copied or doubled to imitate the wrap.

Turning "keep the two ends" into "leave out a middle part" also solves Minimum Operations to Reduce X to Zero.