Maximum Sum Circular Subarray

Medium

Topics
ArrayDivide and ConquerDynamic ProgrammingQueue

nums is circular: the element after the last one is the first one. Return the largest possible sum of a non-empty subarray.

A subarray may wrap around the end, but it may not use any element more than once.

Example 1

10-2132-23
in the best subarrayleft out
The best sum over this array is 3, from the 1 shaded element. The array is circular, so the element after the last one is the first, but no element may be used twice. This answer does not wrap, so it is an ordinary contiguous run and the circularity buys nothing on this input.
The subarray must be non-empty, which matters when every element is negative.
Input:  nums = [1,-2,3,-2]
Output: 3
Explanation: The subarray [3] on its own.

Example 2

50-3152
in the best subarrayleft out
The best sum over this array is 10, from the 2 shaded elements. This answer wraps past the end, and notice what that means: the elements it leaves out form one unbroken block in the middle, which is true of every wrapping subarray.
Input:  nums = [5,-3,5]
Output: 10
Explanation: The subarray wraps: the last 5 followed by the first 5, skipping the -3 in the middle.

Example 3

-30-21-32
in the best subarrayleft out
Input:  nums = [-3,-2,-3]
Output: -2
Explanation: Everything is negative, so the best is the single largest element.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

A valid subarray is one of two shapes and no others. Either it does not wrap, in which case it is an ordinary contiguous run, or it does wrap, in which case the elements it leaves out form a single contiguous run in the middle.

That second observation is the whole problem. Maximising a wrapping subarray is the same as minimising the contiguous run it excludes, so the best wrapping sum is the total of everything minus the smallest contiguous sum. Both the best and the worst contiguous run can be found with the same kind of running scan.

The answer is then the larger of the two shapes. There is one case where that is wrong, and it is the case every first attempt gets wrong: if every element is negative, the smallest contiguous run is the entire array, so "total minus smallest" is zero — the empty subarray, which the problem forbids.

The guard is to notice that this can only happen when the best non-wrapping sum is itself negative, meaning there is no positive element anywhere. In that case the non-wrapping answer is already the single largest element and is correct, so returning it is enough.

Approach

  1. In one scan compute the best contiguous sum, the worst contiguous sum, and the total of all elements.
  2. For the best, keep a running sum that restarts whenever carrying it forward would be worse than starting fresh, and track the maximum seen.
  3. For the worst, do the same with the comparisons reversed.
  4. If the best contiguous sum is negative, every element is negative, so return that best — the largest single element.
  5. Otherwise return the larger of the best contiguous sum and total - worst contiguous sum.

Walkthrough

nums = [5,-3,5]

non-wrapping best
   running: 5, then max(-3, 5-3=2) = 2, then max(5, 2+5=7) = 7
   best = 7        the whole array [5,-3,5]

worst contiguous
   running: 5, then min(-3, 5-3=2) = -3, then min(5, -3+5=2) = 2
   worst = -3      the single [-3]

total = 7

wrapping best = total - worst = 7 - (-3) = 10
   and that 10 IS the wrap: last 5 + first 5, excluding -3

answer max(7, 10) = 10

the all-negative case
nums = [-3,-2,-3]
   best contiguous = -2        the single [-2]
   worst contiguous = -8       the whole array
   total = -8
   total - worst = -8 - (-8) = 0

   0 would mean the EMPTY subarray, which is not allowed.
   best is negative, so every element is negative, and the
   answer is simply best = -2.

why excluding a contiguous run covers every wrap
   a wrapping subarray takes a suffix and a prefix. What it
   leaves out sits strictly between them -- one contiguous
   block. So every wrap corresponds to exactly one excluded
   block, and the best wrap to the worst block.

Complexity

  • Time — O(n): one pass maintaining three running quantities.
  • Space — O(1): a handful of accumulators.

Common Pitfalls

  • Missing the all-negative case, which returns 0 — the empty subarray — instead of the largest element.
  • Duplicating the array and scanning the doubled version. That allows a subarray longer than the original and reuses elements.
  • Initialising the running best and the overall best both to zero, which also smuggles in the empty subarray.
  • Computing the worst contiguous run over the whole array without realising that total - worst is only meaningful when something is left over.
  • Trying every rotation. Correct and quadratic.

Full Solution — all languages

class Solution:
    def maxSubarraySumCircular(self, nums):
        total = 0
        best = worst = nums[0]
        run_best = run_worst = 0

        for v in nums:
            run_best = max(run_best + v, v)
            best = max(best, run_best)

            run_worst = min(run_worst + v, v)
            worst = min(worst, run_worst)

            total += v

        # All negative: "total - worst" would be the empty subarray, which
        # the problem forbids, and best is already the largest element.
        if best < 0:
            return best

        return max(best, total - worst)
SensAI
Beta
Tap the mic to stop voice mode