Maximum Sum Circular Subarray — LeetCode 918 Python Solution
- Problem
- #918
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
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
On a study list
This problem is on Top Interview 150.
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.