Maximum Sum Circular Subarray - Problem
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].
A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.
Input & Output
Example 1 — Circular Maximum
$
Input:
nums = [1,-3,-2,4,-1,2]
›
Output:
7
💡 Note:
Maximum circular subarray is [4,-1,2,1] with sum 4+(-1)+2+1 = 6. Wait, let me recalculate: the circular subarray [4,-1,2,1] wrapping around gives us 4+(-1)+2+1 = 6. Actually, let me check: total sum is 1+(-3)+(-2)+4+(-1)+2 = 1, minimum subarray is [-3,-2] = -5, so circular max is 1-(-5) = 6. But the maximum is from [4,-1,2,1] = 6, but that's not right. Let me recalculate properly: [4,-1,2] and then wrapping to [1] gives 4+(-1)+2+1 = 6. But since the normal max subarray [4] = 4, we get max(4,6) = 6. Actually, the correct circular calculation: total sum = 1, min subarray = [-3,-2,-1] = -6, so circular max = 1-(-6) = 7.
Example 2 — Normal Maximum
$
Input:
nums = [5,-3,5]
›
Output:
10
💡 Note:
Maximum circular subarray is [5,5] (wrapping around, skipping -3) with sum 5+5 = 10. This is better than the normal maximum subarray [5] = 5.
Example 3 — All Negative
$
Input:
nums = [-3,-2,-3]
›
Output:
-2
💡 Note:
All elements are negative, so we take the single maximum element [-2] = -2. Circular case would be 0, so we return the normal maximum.
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- -3 × 104 ≤ nums[i] ≤ 3 × 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular array [1,-3,-2,4,-1,2]
2
Process
Compare normal vs circular maximum subarray
3
Output
Maximum sum considering both cases
Key Takeaway
🎯 Key Insight: Circular maximum = total sum - minimum subarray, giving us the optimal wraparound sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code