Maximum Sum Circular Subarray - Problem
Maximum Sum Circular Subarray

You're given a circular integer array nums of length n. Your task is to find the maximum possible sum of any non-empty subarray within this circular array.

๐Ÿ”„ What makes it circular? The end of the array connects to the beginning - imagine the array arranged in a circle where the last element is adjacent to the first element.

Goal: Return the maximum subarray sum, considering that the subarray can either:
1. Be a regular subarray (contiguous elements without wrapping)
2. Be a circular subarray (wrapping around from end to beginning)

Important: Each element can only be used once in your subarray, and the subarray must be non-empty.

Input & Output

example_1.py โ€” Mixed positive and negative
$ Input: [1, -2, 3, -2]
โ€บ Output: 3
๐Ÿ’ก Note: The maximum subarray is [3] with sum = 3. While we could form a circular subarray [3, -2, 1] = 2, the regular subarray [3] gives us the better result.
example_2.py โ€” Circular case wins
$ Input: [5, -3, 5]
โ€บ Output: 10
๐Ÿ’ก Note: The maximum circular subarray [5, 5] (wrapping around, skipping -3) gives sum = 10, which is better than any regular subarray like [5] = 5.
example_3.py โ€” All negative numbers
$ Input: [-3, -2, -3]
โ€บ Output: -2
๐Ÿ’ก Note: When all numbers are negative, we must pick the single largest element. The circular approach would give sum = 0 (empty array), but we need non-empty subarray, so we return -2.

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 3 ร— 104
  • -3 ร— 104 โ‰ค nums[i] โ‰ค 3 ร— 104
  • Important: The subarray must be non-empty

Visualization

Tap to expand
Circular Theater Seat Selection3Best Single-21-2Circular: Skip bad seats[1] + [3] = 4 (but can't)๐ŸŽญ The AlgorithmStep 1: Find best regular segment: Kadane([1,-2,3,-2]) = 3Step 2: Find worst segment to avoid: Kadane_min([1,-2,3,-2]) = -2Step 3: Circular option: total(0) - min(-2) = 2, Final: max(3,2) = 3
Understanding the Visualization
1
Regular Case
Find the best continuous segment using Kadane's algorithm - like finding the best row in the theater
2
Circular Case
Find the worst segment and avoid it - the remaining seats (wrapping around) give us the best circular option
3
Compare Results
Choose between the best regular segment and the best circular segment
4
Handle Edge Case
If all seats are 'bad' (negative), we must still pick the least bad single seat
Key Takeaway
๐ŸŽฏ Key Insight: Maximum circular subarray = Total sum - Minimum subarray (but handle the all-negative edge case!)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
68.4K Views
High Frequency
~15 min Avg. Time
1.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