Maximum Sum Circular Subarray (LeetCode 918): Solution and Explanation
Given a circular integer array, where the element after the last one is the first one, return the largest possible sum of a non-empty contiguous subarray. Each element may be used at most once, so a subarray can wrap around the end but cannot cover any position twice.
Watch it run step by step
Try your own input and write the code →Intuition
A brute force approach tries every starting index and every length up to n, summing as it goes, for O(n²) time. That is too slow for arrays of 30,000 elements, so you want something linear, and the natural starting point is Kadane's algorithm, which finds the maximum non-circular subarray sum in one pass.
The best circular subarray falls into one of two cases. Either it does not wrap, in which case plain Kadane finds it, or it does wrap, in which case it consists of a prefix and a suffix of the array. A wrapping subarray leaves out some contiguous block in the middle. Since the total sum is fixed, making the prefix plus suffix as large as possible is the same as making the excluded middle block as small as possible. So the best wrapping sum is total - min_subarray_sum, and the minimum subarray sum is just Kadane with min instead of max.
That gives the answer as the larger of the two cases, computed in a single loop that tracks both a running maximum and a running minimum. There is one trap. If every number is negative, the minimum subarray is the whole array, and total - min_sum equals 0, which corresponds to an empty subarray that is not allowed. In that case max_sum is negative, and the correct answer is just max_sum, the largest single element. The reference code handles this by only considering the wrap case when max_sum > 0.
Approach: Kadane's algorithm for max and min
- Initialize
total = 0, setmax_sumandmin_sumtonums[0], and set the running valuescurrent_maxandcurrent_minto 0. - For each
num, updatecurrent_max = max(current_max + num, num), the best subarray ending here, and fold it intomax_sum. - Update
current_min = min(current_min + num, num), the smallest subarray ending here, and fold it intomin_sum. - Add
numtototal. - After the loop, if
max_sum > 0, return the larger ofmax_sumandtotal - min_sum, the best wrapping sum. - Otherwise every element is non-positive, so return
max_sum, the largest single element.
Step-by-step example
nums = [5, -3, 5]
- Start with
max_sum = min_sum = 5,current_max = current_min = 0,total = 0. - Element 5:
current_max = 5,max_sum = 5;current_min = 5,min_sum = 5;total = 5. - Element -3:
current_max = max(2, -3) = 2,max_sumstays 5;current_min = min(2, -3) = -3,min_sum = -3;total = 2. - Element 5:
current_max = max(7, 5) = 7,max_sum = 7;current_min = min(2, 5) = 2,min_sumstays -3;total = 7. max_sumis positive, so the answer ismax(7, 7 - (-3)) = 10, which is the wrapping subarray [5, 5] formed by the last and first elements.
Code: Python, Java, C++
1class Solution:
2 def maxSubarraySumCircular(self, nums: List[int]) -> int:
3 total = 0
4 max_sum = min_sum = nums[0]
5 current_max = current_min = 0
6 for num in nums:
7 current_max = max(current_max + num, num)
8 max_sum = max(max_sum, current_max)
9 current_min = min(current_min + num, num)
10 min_sum = min(min_sum, current_min)
11 total += num
12 return max(max_sum, total - min_sum) if max_sum > 0 else max_sum1class Solution {
2 public int maxSubarraySumCircular(int[] nums) {
3 int total = 0, maxSum = nums[0], minSum = nums[0];
4 int currentMax = 0, currentMin = 0;
5 for (int num : nums) {
6 currentMax = Math.max(currentMax + num, num);
7 maxSum = Math.max(maxSum, currentMax);
8 currentMin = Math.min(currentMin + num, num);
9 minSum = Math.min(minSum, currentMin);
10 total += num;
11 }
12 return maxSum > 0 ? Math.max(maxSum, total - minSum) : maxSum;
13 }
14}1class Solution {
2public:
3 int maxSubarraySumCircular(vector<int>& nums) {
4 int total = 0, maxSum = nums[0], minSum = nums[0];
5 int currentMax = 0, currentMin = 0;
6 for (int num : nums) {
7 currentMax = max(currentMax + num, num);
8 maxSum = max(maxSum, currentMax);
9 currentMin = min(currentMin + num, num);
10 minSum = min(minSum, currentMin);
11 total += num;
12 }
13 return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;
14 }
15};Time and space complexity
O(n)
A single pass updates both Kadane trackers and the total with constant work per element.
O(1)
Only a few running sums are stored, independent of the array length.
Other approaches
Prefix sums with a monotonic deque (time O(n), space O(n))
Conceptually double the array and compute prefix sums. The best subarray ending at position j with length at most n is the prefix at j minus the smallest prefix within the previous n positions, which a monotonic deque maintains in amortized O(1). It is more general, for example when the window length is constrained, but harder to write.
Brute force over all starts (time O(n²), space O(1))
For each start index, extend the subarray around the circle for up to n elements, tracking the running sum and the best seen. It is easy to verify but quadratic.
Common mistakes
- Returning
max(max_sum, total - min_sum)unconditionally. For an all-negative array like [-3, -2, -3], that returns 0 instead of -2. - Computing the max and min trackers in separate loops with shared variables and accidentally reusing
current_maxfor the minimum. - Initializing
max_sumto 0 instead ofnums[0], which also breaks the all-negative case because no subarray sums to 0. - Trying to concatenate the array with itself and running plain Kadane. That can pick a subarray longer than n, using some elements twice.
Frequently asked questions
Why is the wrapping maximum equal to total minus the minimum subarray?
A wrapping subarray is everything except some contiguous middle block. Because the total is fixed, the kept part is largest exactly when the removed block is smallest.
Why check whether max_sum is positive?
If every number is negative, the minimum subarray is the whole array and total - min_sum is 0, which represents choosing nothing. Subarrays must be non-empty, so the answer must be the largest single element instead.
How does this relate to Maximum Subarray?
It is the same Kadane's algorithm, run twice in one loop. The non-circular case is exactly Maximum Subarray, and the circular case is solved by a minimum-subarray Kadane.