Maximum Width Ramp - Problem

Imagine you're looking at an array of numbers where you need to find the widest ramp possible!

A ramp in an integer array nums is a pair of indices (i, j) where:

  • i < j (left index comes before right index)
  • nums[i] <= nums[j] (left value is less than or equal to right value)

The width of such a ramp is simply j - i (the distance between the indices).

Goal: Given an integer array nums, return the maximum width of a ramp. If no ramp exists, return 0.

Example: In array [6,0,8,2,1,5], we can form a ramp from index 1 (value 0) to index 5 (value 5), giving us a width of 4!

Input & Output

example_1.py — Basic Ramp
$ Input: [6,0,8,2,1,5]
Output: 4
💡 Note: The maximum width ramp is from index 1 (value 0) to index 5 (value 5), giving width 5-1=4. Other valid ramps exist like (1,2), (1,3), (1,5), (4,5) but none are wider.
example_2.py — Decreasing Array
$ Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
💡 Note: The maximum width ramp is from index 2 (value 1) to index 9 (value 1), giving width 9-2=7. Even though values are equal, it still forms a valid ramp since 1 <= 1.
example_3.py — No Ramp Possible
$ Input: [10,9,8,7,6,5,4,3,2,1]
Output: 0
💡 Note: This is a strictly decreasing array, so no ramp exists where nums[i] <= nums[j] with i < j. Every element is greater than all elements that come after it.

Visualization

Tap to expand
Mountain Bridge: Maximum Width Ramp608215Longest Bridge: Width = 4StartEndStack of potential starting points: [6, 0, 1]Scan right-to-left to find maximum spanBridge from height 0 to height 5 spans 4 positions
Understanding the Visualization
1
Identify Strategic Points
Mark all potential starting points (decreasing heights from left)
2
Scan from Right
Starting from rightmost point, find the longest bridge possible
3
Build Maximum Bridge
Connect the farthest valid points for maximum span
Key Takeaway
🎯 Key Insight: Use a decreasing monotonic stack to efficiently identify the best starting points, then scan backwards to find the maximum width ramp in linear time!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

We have nested loops where outer loop runs n-1 times and inner loop runs up to n-1 times

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track the maximum width

n
2n
Linear Space

Constraints

  • 2 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 5 × 104
  • Array contains at least 2 elements
Asked in
Google 42 Amazon 38 Apple 25 Microsoft 22
78.3K Views
Medium Frequency
~22 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen