SDE & MLE Prep

918. Maximum Sum Circular Subarray

Problem

nums is circular: its end wraps around to its start. Return the largest sum of a non-empty subarray that uses each element at most once.

Example: [1,-2,3,-2] → 3; [5,-3,5] → 10 (5 + 5 across the wrap)

Constraints: n ≤ 3·10⁴.

A wrap-around subarray = total − (a minimum subarray in the middle). Answer = max(maxKadane, total − minKadane), except when all numbers are negative (then the "wrap" would be empty) → maxKadane.

Complexity: O(n).

class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        cur_max = cur_min = 0
        best_max, best_min = nums[0], nums[0]
        for x in nums:
            cur_max = max(x, cur_max + x)
            best_max = max(best_max, cur_max)
            cur_min = min(x, cur_min + x)
            best_min = min(best_min, cur_min)
        if best_max < 0:
            return best_max
        return max(best_max, sum(nums) - best_min)