Maximum Width Ramp

A ramp in an integer array `nums` is a pair `(i, j)` with `i < j` and `nums[i] <= nums[j]`. Its width is `j - i`. Return the maximum width of a ramp in `nums`, or 0 if there is no ramp.

30:00

Maximum Width Ramp
medium
Free written solution
Topics
Companies

A ramp in an integer array nums is a pair (i, j) with i < j and nums[i] <= nums[j]. Its width is j - i. Return the maximum width of a ramp in nums, or 0 if there is no ramp.

Example 1:
Input: {"nums":[6,0,8,2,1,5]}
Output: 4
Constraints:
  • 2 <= nums.length <= 5 * 10^4

  • 0 <= nums[i] <= 5 * 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[6,0,8,2,1,5]}

A good left end for a ramp is a value lower than everything before it, so the first pass keeps a stack of those "new minimum" indices.

pass 1: collect falling left ends

600182231455

on the stack

j (right end)

ramp being popped

best ramp

stack (bottom to top, values fall)

empty

best width

0

no ramp yet

Variables
VariableValue
n6
stack[]
DepthFunction Call
Stack empty
0/14