Classic problem #962MediumArrayTwo PointersStackMonotonic Stack
Maximum Width Ramp
Real-world version: Widest Span That Does Not FallTracked in this browser only
Read Maximum Width Ramp on LeetCode(opens in a new tab)
The statement here is our own: the same inputs, outputs and technique.
Readings are given as nums.
A span is a pair of positions i before j where the later reading is at least the earlier one. Its width is the difference of the positions.
Return the widest span, or 0 when no span exists.
Examples
Example 1
- Input
- nums = [14, 3, 27, 9, 3, 41]
- Output
- 5
The reading 14 at the front pairs with the 41 at the end, five apart, which is as wide as the list allows.
Example 2
- Input
- nums = [9, 8, 7, 6, 5, 4]
- Output
- 0
Every reading falls below the one before it, so no pair qualifies.
Example 3
- Input
- nums = [7, 7, 7, 7, 7]
- Output
- 4
Equal readings count, since the later one only has to be at least the earlier, so the two ends pair up.
Constraints
- 2 <= nums.length <= 5 * 10^4
- 0 <= nums[i] <= 5 * 10^4
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
Python
def max_width_ramp(nums: list[int]) -> int:Java
public int maxWidthRamp(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Shortest Unsorted Continuous SubarrayReal-world version: Shortest Stretch to Re-sortMedium
- Shortest Subarray to be Removed to Make Array SortedReal-world version: Cutting One Stretch to Leave the Gauges RisingMedium
- Trapping Rain WaterReal-world version: Level Flood CapacityHard
- Create Maximum NumberReal-world version: The Largest Reading From Two TapesHard