Back to ArraysMaximum Sum Circular Subarray
Medium

Maximum Sum Circular Subarray

MediumRecommendedKadane's Algorithm

Given a circular array (the end connects back to the start), find the maximum possible sum of a non-empty contiguous subarray, where the subarray may wrap around the end.

Examples

Example 1

Input:
nums = [1,-2,3,-2]
Output:
3

Explanation: The best subarray doesn't need to wrap at all — [3] alone gives the maximum sum of 3.

Example 2

Input:
nums = [5,-3,5]
Output:
10

Explanation: Wrapping around — taking the last 5, then the first 5 (skipping the -3 in the middle) — gives 5 + 5 = 10, which beats any non-wrapping subarray.

Example 3

Input:
nums = [-3,-2,-3]
Output:
-2

Explanation: Every element is negative, so wrapping can only ever make things worse. The best answer is the least negative single element, -2 — the edge case where the totalSum-minus-minimum trick would otherwise wrongly imply an empty subarray, which isn't allowed.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4

Follow-up

Can you solve it using a single pass that tracks both the running maximum and running minimum subarray sums simultaneously, instead of two separate passes?

Loading editor…

Code execution is coming soon.