Maximum Sum Circular Subarray

Medium Arrays & Hashing Kadane's Algorithm

Maximum Sum Circular Subarray is a medium arrays & hashing problem solved with the kadane's algorithm pattern. The best approach, optimal (kadane for max and min), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (every start, every length) up.

Problem

You are given an integer array nums of length n that is circular: after the last element nums[n - 1] comes the first element nums[0] again.

A subarray is a run of consecutive positions around this circle. It may cross the end and continue from the start, but it may not use any position more than once, so it contains between 1 and n elements.

Return the largest possible sum of a non-empty subarray.

Examples

Example 1

Input
nums = [3, -2, 4, -5, 2]
Output
7
Why
Wrap around the end: 2, 3, -2, 4 (the last element followed by the first three) adds up to 7. The best piece that does not wrap, 3, -2, 4, only reaches 5.

Example 2

Input
nums = [5, -1, 4]
Output
9
Why
The whole array gives 5 - 1 + 4 = 8, but wrapping from the last element to the first, 4 then 5, skips the -1 and gives 9.

Example 3

Input
nums = [-3, -1, -4]
Output
-1
Why
Every number is negative, and the subarray must be non-empty, so the best is the single largest number, -1.

Constraints

  • n == nums.length
  • 1 <= n <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 26 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (every start, every length)O(n²)O(1)
Best prefix plus best suffixO(n)O(n)
Optimal (Kadane for max and min)O(n)O(1)

1Brute force (every start, every length)

TimeO(n²)n starts times up to n lengths, each in constant time thanks to the running sum.
SpaceO(1)Only the running sum and the best value.

Try every starting index i and grow the subarray one element at a time around the circle, up to n elements, using index (i + len) % n to wrap. Keep a running sum and remember the largest sum seen. That checks all n times n circular subarrays directly.

  1. Set best to the smallest possible value.
  2. For each start i from 0 to n - 1: set sum = 0.
  3. For len from 0 to n - 1: add nums[(i + len) % n] to sum and update best.
  4. Return best.
class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int best = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int len = 0; len < n; len++) {
                sum += nums[(i + len) % n];
                best = Math.max(best, sum);
            }
        }
        return best;
    }
}

2Best prefix plus best suffix

TimeO(n)Three linear passes: Kadane, the suffix table, and the prefix sweep.
SpaceO(n)The rightBest array has n + 1 entries.

Split the answers into two kinds. A subarray that does not wrap is found by Kadane's algorithm: keep the best sum of a subarray ending at the current index, either extending the previous one or starting fresh. A subarray that wraps is a prefix nums[0..i] glued to a suffix nums[j..n-1] with j > i. Precompute rightBest[j], the largest suffix sum starting at j or later. Then sweep i from left to right with a running prefix sum, and the best wrap for that prefix is prefix + rightBest[i + 1]. The answer is the larger of the two kinds.

  1. Kadane: cur = max(x, cur + x) for each x, and best = the largest cur seen.
  2. Build rightBest from the right: suffix += nums[j]; rightBest[j] = max(rightBest[j + 1], suffix).
  3. Sweep i from 0 to n - 2 with prefix += nums[i] and best = max(best, prefix + rightBest[i + 1]).
  4. Return best.
class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int best = nums[0], cur = 0;
        for (int x : nums) {
            cur = Math.max(x, cur + x);
            best = Math.max(best, cur);
        }
        int[] rightBest = new int[n + 1];
        rightBest[n] = Integer.MIN_VALUE;
        int suffix = 0;
        for (int j = n - 1; j >= 0; j--) {
            suffix += nums[j];
            rightBest[j] = Math.max(rightBest[j + 1], suffix);
        }
        int prefix = 0;
        for (int i = 0; i + 1 < n; i++) {
            prefix += nums[i];
            best = Math.max(best, prefix + rightBest[i + 1]);
        }
        return best;
    }
}

3Optimal (Kadane for max and min)

TimeO(n)One pass over the array with constant work per element.
SpaceO(1)Five integer variables.

A wrapping subarray is the whole array minus one contiguous middle piece, so its sum is total minus that piece. It is largest when the removed piece is the minimum-sum subarray, which a second Kadane, run with min instead of max, finds in the same pass. So the answer is max(maxSum, total - minSum). One trap: if every number is negative, the minimum subarray is the whole array and total - minSum is 0, the sum of an empty subarray, which is not allowed. In that case maxSum is negative and is the answer by itself.

  1. Track total, curMax, maxSum, curMin and minSum in one pass.
  2. For each x: curMax = max(x, curMax + x), maxSum = max(maxSum, curMax); curMin = min(x, curMin + x), minSum = min(minSum, curMin); total += x.
  3. If maxSum < 0, every number is negative: return maxSum.
  4. Otherwise return max(maxSum, total - minSum).
class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int total = 0;
        int curMax = 0, maxSum = nums[0];
        int curMin = 0, minSum = nums[0];
        for (int x : nums) {
            curMax = Math.max(x, curMax + x);
            maxSum = Math.max(maxSum, curMax);
            curMin = Math.min(x, curMin + x);
            minSum = Math.min(minSum, curMin);
            total += x;
        }
        if (maxSum < 0) return maxSum;
        return Math.max(maxSum, total - minSum);
    }
}

Edge cases to test

  • All numbers negative: total minus the minimum subarray would mean taking nothing, which is not allowed; the answer is the largest single number
  • A single element: the answer is that element
  • The best subarray is the whole array (all numbers positive)
  • The best subarray does not wrap at all, so the plain maximum must still be considered
  • A subarray may not use any position twice, so its length is at most n

Hints

Hint 1

A subarray of a circular array either stays inside nums or wraps around the end. The first kind is the classic maximum subarray.

Hint 2

A wrapping subarray is a prefix plus a suffix of nums. Equivalently, it is the whole array with one contiguous middle piece removed.

Hint 3

To make total - (removed piece) as big as possible, remove the minimum-sum subarray. Watch out when every number is negative.

FAQ

What is the best time complexity for Maximum Sum Circular Subarray?

Optimal (Kadane for max and min) runs in O(n) time and O(1) extra space. One pass over the array with constant work per element.

Which pattern does Maximum Sum Circular Subarray use?

It is a arrays & hashing problem that uses the kadane's algorithm pattern. Other problems with the same pattern: Kadane's Algorithm - Simple, Find minimum subarray sum, Kadane's Algo - Circular Array - No Extra Space.

Is there a brute force solution for Maximum Sum Circular Subarray?

Yes. Brute force (every start, every length) takes O(n²) time and O(1) space. Try every starting index i and grow the subarray one element at a time around the circle, up to n elements, using index (i + len) % n to wrap.

Which edge cases should I test for Maximum Sum Circular Subarray?

All numbers negative: total minus the minimum subarray would mean taking nothing, which is not allowed; the answer is the largest single number; A single element: the answer is that element; The best subarray is the whole array (all numbers positive); The best subarray does not wrap at all, so the plain maximum must still be considered; A subarray may not use any position twice, so its length is at most n.