Maximum Width Ramp — LeetCode 962 Python Solution
MediumStackArrayTwo PointersMonotonic Stack
- Problem
- #962
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.
Example
- Input
- nums = [6,0,8,2,1,5]
- Output
- 4
- Explanation
- The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
Python solution
Python
class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
stk = []
for i, v in enumerate(nums):
if not stk or nums[stk[-1]] > v:
stk.append(i)
ans = 0
for i in range(len(nums) - 1, -1, -1):
while stk and nums[stk[-1]] <= nums[i]:
ans = max(ans, i - stk.pop())
if not stk:
break
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n represents the length of \textit{nums} auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 962. Maximum Width Ramp is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
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 962. Maximum Width Ramp?
- LeetCode 962. Maximum Width Ramp is rated Medium on LeetCode.
- What is the time complexity of LeetCode 962. Maximum Width Ramp?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 962. Maximum Width Ramp?
- The Python solution on this page uses O(n), where n represents the length of \textit{nums} auxiliary space.
- What topics does LeetCode 962. Maximum Width Ramp cover?
- LeetCode 962. Maximum Width Ramp is tagged Stack, Array, Two Pointers and Monotonic Stack on LeetCode.