MediumNo. 0918

Maximum Sum Circular Subarray — LeetCode 918 Python Solution

Pattern
Stack
Topics
Queue, Array, Divide and Conquer, Dynamic Programming, Monotonic Queue
On a study list
Top Interview 150
Reading time
2 min

The problem

Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums. A circular array means the end of the array connects to the beginning of the array.

Example

Input
nums = [1,-2,3,-2]
Output
3
Explanation
Subarray [3] has maximum sum 3.

Python solution

PythonSolution
class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        pmi, pmx = 0, -inf
        ans, s, smi = -inf, 0, inf
        for x in nums:
            s += x
            ans = max(ans, s - pmi)
            smi = min(smi, s - pmx)
            pmi = min(pmi, s)
            pmx = max(pmx, s)
        return max(ans, s - smi)

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 918. Maximum Sum Circular Subarray is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 918. Maximum Sum Circular Subarray?

LeetCode 918. Maximum Sum Circular Subarray is rated Medium on LeetCode.

What is the time complexity of LeetCode 918. Maximum Sum Circular Subarray?

The Python solution on this page runs in O(n), where n is the length of the array.

What is the space complexity of LeetCode 918. Maximum Sum Circular Subarray?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 918. Maximum Sum Circular Subarray cover?

LeetCode 918. Maximum Sum Circular Subarray is tagged Queue, Array, Divide and Conquer, Dynamic Programming and Monotonic Queue on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.