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 INPUT nums = [6, 0, 8, 2, 1, 5] i=0 i=1 i=2 i=3 i=4 i=5 6 0 8 2 1 5 Ramp: (i, j) where i < j and nums[i] <= nums[j] Best Ramp: i=1, j=5 width = 5-1 = 4 nums[1] = 0 nums[5] = 5 0 <= 5 [OK] Width = 5 - 1 = 4 ALGORITHM STEPS 1 Build Decreasing Stack Store indices of decreasing values stack = [0, 1] (vals: 6, 0) 2 Traverse Right to Left Start from end, find valid pairs j = 5, 4, 3, 2, 1, 0 3 Pop Valid Pairs While nums[stack.top] <= nums[j] Update max width = j - i 4 Track Maximum Keep best width found Execution Trace: j=5: nums[5]=5 >= nums[1]=0 width = 5-1 = 4 [OK] j=5: nums[5]=5 < nums[0]=6 skip (not valid) j=2: nums[2]=8 >= nums[0]=6 width = 2-0 = 2 (not max) FINAL RESULT Maximum Width Ramp Found: 6 0 8 2 1 5 0 1 2 3 4 5 Width = 4 OUTPUT 4 Verification: i = 1, j = 5 nums[1]=0 <= nums[5]=5 [OK] max_width = 5 - 1 = 4 Time: O(n) | Space: O(n) Key Insight: Use a monotonic decreasing stack to store potential starting indices. By traversing from right to left, we can efficiently find the maximum width ramp. Each element is pushed/popped at most once, achieving O(n) time complexity. The stack ensures we only consider valid starting points. TutorialsPoint - Maximum Width Ramp | Optimal Solution (Monotonic Stack)
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