Maximum of Minimum Values in All Subarrays — LeetCode 1950 Python Solution
MediumLeetCode PremiumStackArrayMonotonic Stack
- Problem
- #1950
- Pattern
- Stack
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given an integer array nums of size n. You are asked to solve n queries for each integer i in the range 0 <= i < n.
Example
- Input
- nums = [0,1,2,4]
- Output
- [4,2,1,0]
- Explanation
- i=0:
Python solution
Python
class Solution:
def findMaximums(self, nums: List[int]) -> List[int]:
n = len(nums)
left = [-1] * n
right = [n] * n
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] >= x:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
while stk and nums[stk[-1]] >= nums[i]:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
ans = [0] * n
for i in range(n):
m = right[i] - left[i] - 1
ans[m - 1] = max(ans[m - 1], nums[i])
for i in range(n - 2, -1, -1):
ans[i] = max(ans[i], ans[i + 1])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1950. Maximum of Minimum Values in All Subarrays is filed here because LeetCode tags it Stack, 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 1950. Maximum of Minimum Values in All Subarrays?
- LeetCode 1950. Maximum of Minimum Values in All Subarrays is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1950. Maximum of Minimum Values in All Subarrays?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1950. Maximum of Minimum Values in All Subarrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1950. Maximum of Minimum Values in All Subarrays cover?
- LeetCode 1950. Maximum of Minimum Values in All Subarrays is tagged Stack, Array and Monotonic Stack on LeetCode.
- Is LeetCode 1950. Maximum of Minimum Values in All Subarrays a premium problem?
- Yes. LeetCode 1950. Maximum of Minimum Values in All Subarrays is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.