◀ THE GRIND — GREEDY

Maximum Sum Circular Subarray

MEDIUM✓ CHIP-TIMEDLC #918 — FULL STATEMENT ↗

The drill: Numbers sit in a circle — a run may wrap past the last index back to the front. Pick a nonempty contiguous run of that circular arrangement with the largest possible sum.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

Numbers are arranged in a circle this time — after the last index, the sequence loops right back to the first. A contiguous run in this circular layout may wrap around that seam, continuing past the end into the front.

The task is finding the largest possible sum from one non-empty contiguous run of the circle — whether that run wraps around the seam or stays entirely within the normal left-to-right order.

A run may span at most the full circle once; it never doubles back over the same element twice. Only the best achievable sum matters as the answer.

EX 01
nums = [5, -3, 5]
10
WRAP CONNECTS THE TWO OUTER FIVES
EX 02
nums = [-4, -2, -6]
-2
ALL NEGATIVE — LEAST BAD SINGLE ELEMENT
EX 03
nums = [1, -2, 3, -2]
3
NO WRAP NEEDED, PLAIN KADANE WINS
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

A wraparound run is really two pieces glued at the seam: a suffix plus a prefix. If the wraparound run is the best one, what does the piece you're NOT taking — the middle you skip over — look like?

HINT 2 THE STRUCTURE

The skipped middle is just an ordinary, non-wrapping contiguous run. So a circular run's sum equals the total sum minus some ordinary run's sum — and you want that ordinary run to be as negative as possible.

HINT 3 ONE STEP FROM THE ANSWER

Run Kadane's rule twice: once for the largest ordinary run, once for the smallest. The circular answer is max(largest, total − smallest) — unless every number is negative, in which case skip the subtraction and just report the largest single run, since 'total − smallest' would otherwise leave nothing picked.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE WRAP OR THE RUNPATTERN · KADANE TWICE, MIRROREDnums = [5, -3, 5] (circular)
5
-3
5
CURMAX · MAXSUM · CURMIN · MINSUM · TOTAL
curMax5
maxSum5
curMin5
minSum5
total7
STEP 1

Circle [5, -3, 5], total 7. Both a max-Kadane and a min-Kadane start at the first value, 5.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/maximum-sum-circular-subarray.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        total = sum(nums)
        curMax = maxSum = nums[0]
        curMin = minSum = nums[0]
        for num in nums[1:]:
            curMax = max(num, curMax + num)
            maxSum = max(maxSum, curMax)
            curMin = min(num, curMin + num)
            minSum = min(minSum, curMin)
        if maxSum < 0:
            return maxSum
        return max(maxSum, total - minSum)
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED