Maximum Width Ramp - 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.

Given an integer array nums, return the maximum width of a ramp in nums.

If there is no ramp in nums, return 0.

Input & Output

Example 1 — Basic Ramp
$ Input: nums = [6,0,8,2,1,5]
Output: 4
💡 Note: The maximum width ramp is from index 1 to index 5: nums[1] = 0 <= nums[5] = 5, width = 5 - 1 = 4
Example 2 — Decreasing Array
$ Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
💡 Note: The maximum width ramp is from index 2 to index 9: nums[2] = 1 <= nums[9] = 1, width = 9 - 2 = 7
Example 3 — No Valid Ramp
$ Input: nums = [10,9,8,7,6]
Output: 0
💡 Note: Array is strictly decreasing, so no valid ramp exists where nums[i] <= nums[j] with i < j

Constraints

  • 2 ≤ nums.length ≤ 5 × 104
  • 0 ≤ nums[i] ≤ 5 × 104

Visualization

Tap to expand
Maximum Width Ramp Problem608215012345Valid Ramp: nums[1] = 0 <= nums[5] = 5Width = 5 - 1 = 4Goal: Find maximum width j - i where i < j and nums[i] <= nums[j]Output: 4
Understanding the Visualization
1
Input Array
Given array [6,0,8,2,1,5] with indices 0-5
2
Find Ramps
Identify all valid pairs (i,j) where i < j and nums[i] <= nums[j]
3
Maximum Width
Return the largest width j - i among all valid ramps
Key Takeaway
🎯 Key Insight: Use a monotonic decreasing stack to efficiently track potential ramp starting positions
Asked in
Google 15 Facebook 12 Amazon 8
78.5K Views
Medium Frequency
~25 min Avg. Time
2.2K 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