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
Maximum Sum Circular Subarray INPUT 1 -3 -2 4 -1 2 nums = [1,-3,-2,4,-1,2] Length n = 6 End connects to beginning (circular array) ALGORITHM STEPS 1 Find Max Normal Subarray Use Kadane's algorithm 2 Find Min Subarray Kadane's for minimum 3 Circular Sum Total - MinSum = wrap sum 4 Return Maximum max(normalMax, circularMax) Calculations: Total Sum = 1 Max Normal = 5 [4,-1,2] Min Subarray = -6 [-3,-2,-1] Circular = 1-(-6) = 7 Result = max(5, 7) = 7 FINAL RESULT Optimal Circular Subarray: 1 -3 -2 4 -1 2 Wraps: [4,-1,2] + [1] = 4 + (-1) + 2 + 1 = 6 Best: [2,1] wrap + [4] = 2 + 1 + 4 = 7 Output: 7 Key Insight: Circular max subarray either: (1) doesn't wrap (normal Kadane), or (2) wraps around edges. For wrap case: Max = TotalSum - MinSubarray. The minimum subarray is what we "skip" in the middle. TutorialsPoint - Maximum Sum Circular Subarray | Optimized Single Pass O(n)
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.5K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen