MediumNo. 0962
Maximum Width Ramp — LeetCode 962 Python Solution
- Pattern
- Stack
- Topics
- Stack, Array, Two Pointers, Monotonic 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)where n represents the length of nums
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
| No. | Problem | Difficulty |
|---|---|---|
| 0042 | Trapping Rain Water | Hard |
| 0321 | Create Maximum Number | Hard |
| 0581 | Shortest Unsorted Continuous Subarray | Medium |
| 1574 | Shortest Subarray to be Removed to Make Array Sorted | Medium |
| 1793 | Maximum Score of a Good Subarray | Hard |
| 0143 | Reorder List | Medium |
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.