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 [1,4,2] (wrapping around, excluding the minimum subarray [-3,-2,-1]) with sum 1+4+2 = 7. The normal maximum subarray is [4] = 4. Since 7 > 4, we return 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code