Maximum Sum Circular Subarray
MediumTop Interview 150 GreedyTwo SigmaProblem
The array nums is arranged in a circle: after the last element comes the first one again.
A run is a non-empty stretch of neighbouring elements, and it may wrap from the end back to the start. A run uses each element at most once. Return the largest sum any run can have.
Constraints
- 1 ≤ nums.length ≤ 30000
- −30000 ≤ nums[i] ≤ 30000
- The total is at most 9 × 10^8 in size, so int is safe
Examples: pick one to animate
Solutions
Time: A single pass updates all five numbers per element.
Space: Only a handful of integers are stored.
A run on the circle either stays inside the array (an ordinary best run) or wraps. A wrapping run is everything except one ordinary stretch in the middle, so its sum is total minus that stretch; make the stretch as small as possible. Track both the best run and the worst run with Kadane's idea. If every number is negative the worst run is the whole array and the wrap would be empty, so return best then.