Coding Interview PatternsMaximum Width Ramp
MediumMonotonic Stack
Maximum Width Ramp
Explanation & Solution
Description
Given an integer array nums, a ramp is a pair (i, j) where i < j and nums[i] <= nums[j]. Return the maximum width j - i of a ramp in nums, or 0 if no ramp exists.
Input:nums = [6,0,8,2,1,5]
0
6
1
0
2
8
3
2
4
1
5
5
Output: 4
Explanation: The maximum width ramp is at pair (1, 5): nums[1] = 0 <= nums[5] = 5, so the width is 5 - 1 = 4.
Constraints
2 <= nums.length <= 5 * 10⁴0 <= nums[i] <= 5 * 10⁴
Approach
Monotonic Stack pattern
1. Build a Monotonic Decreasing Stack
- Iterate through the array from left to right
- Push index
ionto the stack only ifnums[i]is strictly less than the value at the current top of the stack - This captures all candidate left endpoints — any optimal left index must appear in this decreasing sequence
2. Why Only Decreasing Values Are Candidates
- If
nums[a] <= nums[b]anda < b, thenais always a better left endpoint thanb(it gives a wider ramp) - So we only need indices where values are strictly decreasing — later, larger-or-equal values are dominated by earlier ones
3. Traverse From Right to Left
- Start from the rightmost index
j = n - 1and move leftward - For each
j, check ifnums[stack.top] <= nums[j] - If so, pop the stack top as index
iand recordj - ias a candidate answer
4. Pop and Record Maximum Width
- Each time we pop, compute
j - iand updatemaxWidth - We can safely pop because no future (smaller)
jcould produce a wider ramp with this samei - Continue popping while the condition holds — multiple left candidates may pair with the same
j
5. Return the Result
- After the traversal completes,
maxWidthcontains the widest ramp found - If no ramp exists (e.g., strictly decreasing array),
maxWidthremains0
Key Insight
The monotonic decreasing stack captures all useful left endpoints, and scanning from right to left ensures we try the widest possible ramp first for each candidate. Each index is pushed and popped at most once, giving O(n) time and O(n) space complexity.
Visualization
Input:
[6, 0, 8, 2, 1, 5]
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps