918. Maximum Sum Circular Subarray
Asked at 12Amazon30Microsoft30Google27Meta24Apple22Bloomberg22Infosys45Two Sigma90MakeMyTrip65Sprinklr54Goldman Sachs28TikTok26
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)
assert Solution().maxSubarraySumCircular([1, -2, 3, -2]) == 3
assert Solution().maxSubarraySumCircular([5, -3, 5]) == 10
assert Solution().maxSubarraySumCircular([-3, -2, -3]) == -2
class Solution {
public int maxSubarraySumCircular(int[] nums) {
int curMax = 0, curMin = 0, bestMax = nums[0], bestMin = nums[0], total = 0;
for (int x : nums) {
curMax = Math.max(x, curMax + x);
bestMax = Math.max(bestMax, curMax);
curMin = Math.min(x, curMin + x);
bestMin = Math.min(bestMin, curMin);
total += x;
}
return bestMax < 0 ? bestMax : Math.max(bestMax, total - bestMin);
}
}
func maxSubarraySumCircular(nums []int) int {
curMax, curMin, total := 0, 0, 0
bestMax, bestMin := nums[0], nums[0]
for _, x := range nums {
curMax = max(x, curMax+x)
bestMax = max(bestMax, curMax)
curMin = min(x, curMin+x)
bestMin = min(bestMin, curMin)
total += x
}
if bestMax < 0 {
return bestMax // all negative: the wrap-around case would be empty
}
return max(bestMax, total-bestMin) // a wrapping subarray = total minus a middle one
}