InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Maximum Sum Circular Subarray

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug