Maximum Sum Circular Subarray
Medium
Topics
nums is circular: the element after the last one is the first one. Return the largest possible sum of a non-empty subarray.
A subarray may wrap around the end, but it may not use any element more than once.
Example 1
Input: nums = [1,-2,3,-2] Output: 3 Explanation: The subarray [3] on its own.
Example 2
Input: nums = [5,-3,5] Output: 10 Explanation: The subarray wraps: the last 5 followed by the first 5, skipping the -3 in the middle.
Example 3
Input: nums = [-3,-2,-3] Output: -2 Explanation: Everything is negative, so the best is the single largest element.
Constraints
- 1 <= nums.length <= 3 * 10^4
- -3 * 10^4 <= nums[i] <= 3 * 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
A valid subarray is one of two shapes and no others. Either it does not wrap, in which case it is an ordinary contiguous run, or it does wrap, in which case the elements it leaves out form a single contiguous run in the middle.
That second observation is the whole problem. Maximising a wrapping subarray is the same as minimising the contiguous run it excludes, so the best wrapping sum is the total of everything minus the smallest contiguous sum. Both the best and the worst contiguous run can be found with the same kind of running scan.
The answer is then the larger of the two shapes. There is one case where that is wrong, and it is the case every first attempt gets wrong: if every element is negative, the smallest contiguous run is the entire array, so "total minus smallest" is zero — the empty subarray, which the problem forbids.
The guard is to notice that this can only happen when the best non-wrapping sum is itself negative, meaning there is no positive element anywhere. In that case the non-wrapping answer is already the single largest element and is correct, so returning it is enough.
Approach
- In one scan compute the best contiguous sum, the worst contiguous sum, and the total of all elements.
- For the best, keep a running sum that restarts whenever carrying it forward would be worse than starting fresh, and track the maximum seen.
- For the worst, do the same with the comparisons reversed.
- If the best contiguous sum is negative, every element is negative, so return that best — the largest single element.
- Otherwise return the larger of the best contiguous sum and
total - worst contiguous sum.
Walkthrough
nums = [5,-3,5]
non-wrapping best
running: 5, then max(-3, 5-3=2) = 2, then max(5, 2+5=7) = 7
best = 7 the whole array [5,-3,5]
worst contiguous
running: 5, then min(-3, 5-3=2) = -3, then min(5, -3+5=2) = 2
worst = -3 the single [-3]
total = 7
wrapping best = total - worst = 7 - (-3) = 10
and that 10 IS the wrap: last 5 + first 5, excluding -3
answer max(7, 10) = 10
the all-negative case
nums = [-3,-2,-3]
best contiguous = -2 the single [-2]
worst contiguous = -8 the whole array
total = -8
total - worst = -8 - (-8) = 0
0 would mean the EMPTY subarray, which is not allowed.
best is negative, so every element is negative, and the
answer is simply best = -2.
why excluding a contiguous run covers every wrap
a wrapping subarray takes a suffix and a prefix. What it
leaves out sits strictly between them -- one contiguous
block. So every wrap corresponds to exactly one excluded
block, and the best wrap to the worst block.Complexity
- Time — O(n): one pass maintaining three running quantities.
- Space — O(1): a handful of accumulators.
Common Pitfalls
- Missing the all-negative case, which returns
0— the empty subarray — instead of the largest element. - Duplicating the array and scanning the doubled version. That allows a subarray longer than the original and reuses elements.
- Initialising the running best and the overall best both to zero, which also smuggles in the empty subarray.
- Computing the worst contiguous run over the whole array without realising that
total - worstis only meaningful when something is left over. - Trying every rotation. Correct and quadratic.
Full Solution — all languages
class Solution:
def maxSubarraySumCircular(self, nums):
total = 0
best = worst = nums[0]
run_best = run_worst = 0
for v in nums:
run_best = max(run_best + v, v)
best = max(best, run_best)
run_worst = min(run_worst + v, v)
worst = min(worst, run_worst)
total += v
# All negative: "total - worst" would be the empty subarray, which
# the problem forbids, and best is already the largest element.
if best < 0:
return best
return max(best, total - worst)import java.util.*;
class Solution {
public int maxSubarraySumCircular(int[] nums) {
int total = 0;
int best = nums[0], worst = nums[0];
int runBest = 0, runWorst = 0;
for (int v : nums) {
runBest = Math.max(runBest + v, v);
best = Math.max(best, runBest);
runWorst = Math.min(runWorst + v, v);
worst = Math.min(worst, runWorst);
total += v;
}
if (best < 0) return best;
return Math.max(best, total - worst);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxSubarraySumCircular(vector<int>& nums) {
int total = 0;
int best = nums[0], worst = nums[0];
int runBest = 0, runWorst = 0;
for (int v : nums) {
runBest = max(runBest + v, v);
best = max(best, runBest);
runWorst = min(runWorst + v, v);
worst = min(worst, runWorst);
total += v;
}
if (best < 0) return best;
return max(best, total - worst);
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxSubarraySumCircular = function(nums) {
let total = 0;
let best = nums[0], worst = nums[0];
let runBest = 0, runWorst = 0;
for (const v of nums) {
runBest = Math.max(runBest + v, v);
best = Math.max(best, runBest);
runWorst = Math.min(runWorst + v, v);
worst = Math.min(worst, runWorst);
total += v;
}
if (best < 0) return best;
return Math.max(best, total - worst);
};