InterviewPrepKit

Home / Coding / Greedy

Maximum Sum Circular Subarray

medium Original β†—
Solving tips
  • Split by shape: the answer either doesn't wrap (ordinary Kadane max) or wraps (total minus the minimum subarray, found by an inverted Kadane).
  • Run both Kadanes and the total in a single pass, then return max(maxSum, total - minSum).
  • Guard the all-negative case: if maxSum < 0, return maxSum, because total - minSum would give 0 (an empty, illegal selection).
  • Target O(n) time and O(1) space; remember the min-Kadane uses min(x, cur_min + x), not max.

Problem

Given a circular integer array nums, find the maximum possible sum of a non-empty subarray. Circular means the array wraps: the element after index n-1 is index 0, so a subarray may start near the end and continue from the beginning. A subarray may not include the same element twice (its length is at most n).

Examples

  • nums = [1,-2,3,-2] β†’ 3 β€” the plain subarray [3].
  • nums = [5,-3,5] β†’ 10 β€” wrap around: [5, 5] using indices 2 and 0 (skipping the -3).
  • nums = [-3,-2,-3] β†’ -2 β€” all negative, so the best is the single largest element -2.

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4

O(n) is expected. The all-negative array is the essential edge case that a naive wrap formula gets wrong.

Think about it first

Hint 1 The optimal subarray is one of two shapes: it does not wrap (an ordinary contiguous run), or it does wrap around the ends. Solve the non-wrapping case with the standard maximum-subarray method.
Hint 2 A wrapping maximum keeps a prefix and a suffix while excluding a middle chunk. To maximize what you keep, you want to exclude the middle chunk with the smallest sum. How does that relate to the total?
Hint 3 Wrapping max = total - (minimum subarray sum). Answer = max(maxKadane, total - minKadane). But if every number is negative, total - minKadane becomes 0 (an empty selection) β€” guard that by falling back to maxKadane.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.