Maximum Sum Circular Subarray (LeetCode 918): Solution and Explanation

Medium
Array
Divide And Conquer
Dynamic Programming
Queue
Monotonic Queue

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Initialize total = 0, set max_sum and min_sum to nums[0], and set the running values current_max and current_min to 0.
  2. For each num, update current_max = max(current_max + num, num), the best subarray ending here, and fold it into max_sum.
  3. Update current_min = min(current_min + num, num), the smallest subarray ending here, and fold it into min_sum.
  4. Add num to total.
  5. After the loop, if max_sum > 0, return the larger of max_sum and total - min_sum, the best wrapping sum.
  6. Otherwise every element is non-positive, so return max_sum, the largest single element.

Step-by-step example

nums = [5, -3, 5]
  1. Start with max_sum = min_sum = 5, current_max = current_min = 0, total = 0.
  2. Element 5: current_max = 5, max_sum = 5; current_min = 5, min_sum = 5; total = 5.
  3. Element -3: current_max = max(2, -3) = 2, max_sum stays 5; current_min = min(2, -3) = -3, min_sum = -3; total = 2.
  4. Element 5: current_max = max(7, 5) = 7, max_sum = 7; current_min = min(2, 5) = 2, min_sum stays -3; total = 7.
  5. max_sum is positive, so the answer is max(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_sum

Time and space complexity

Time

O(n)

A single pass updates both Kadane trackers and the total with constant work per element.

Space

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_max for the minimum.
  • Initializing max_sum to 0 instead of nums[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.