Skip to content

DP — Maximum Sum Circular Subarray ​

↗ LeetCode: Maximum Sum Circular Subarray · Medium · pattern chapter →

Asked atAmazonGoogleMeta

Max subarray sum in a circular array.

Example 1 — nums=[1,-2,3,-2] → 3 ([3], no wrap) Example 2 — nums=[5,-3,5] → 10 (wrap: [5]…[5]) Example 3 — nums=[-3,-2,-3] → -2 (all-negative: must return single largest)

Constraints — 1 ≤ n ≤ 3·10⁴. Brute is O(n²) doubled-array Kadane — 10⁹ ops = TLE. Two-Kadane trick is O(n) = 3·10⁴ ops = <1ms.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Brute doubled-array Kadane ​

Intuition. Concatenate nums with itself, then run Kadane restricted to windows of size ≤ n. O(n²).

Complexity — Time O(n²); Space O(n). TLE past n=3000. In an interview say "wrap-around = complement of a non-wrap minimum subarray → two-pass Kadane on max and min → O(n)."


Approach 2 — Kadane on both max and min (canonical) ​

Insight. Answer is either:

  • Non-wrapping: standard Kadane max.
  • Wrapping: totalSum − minSubarraySum (peel off the worst middle chunk).

Edge case. If all negative, total − minSubSum = 0 (empty subarray) → return kadaneMax instead.

java
int maxSubarraySumCircular(int[] nums) {
    int total = 0, curMax = 0, curMin = 0, maxS = nums[0], minS = nums[0];
    for (int x : nums) {
        total += x;
        curMax = Math.max(curMax + x, x);
        maxS = Math.max(maxS, curMax);
        curMin = Math.min(curMin + x, x);
        minS = Math.min(minS, curMin);
    }
    return maxS > 0 ? Math.max(maxS, total - minS) : maxS;
}
Execution Trace
Kadane on both max and min (canonical)
i10-2132-23phase = start
Step 1 / 3Initialize scan.

Complexity — Time O(n); Space O(1). Say aloud in an interview: "same cyclic-to-linear reduction as House Robber II — two linear DPs cover both regimes."


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceGrade
Doubled KadaneO(n²)O(n)TLE past n=3000
Kadane × 2 + edgeO(n)O(1)Canonical

When to use which ​

  • Circular → dual Kadane.
  • Linear → standard Kadane.
  • "Return the subarray" → track indices.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help