Maximum Width Ramp

MediumStackmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums, a **ramp** is a pair of indices (i, j) with i < j and nums[i] <= nums[j]. Its width is j - i. Return the maximum width over all ramps in nums, or 0 if there is no ramp. Target O(n) or O(n log n) time.

Examples

Input: nums = [6,0,8,2,1,5]
Output: 4
The widest ramp is (1, 5): nums[1] = 0 <= nums[5] = 5.
Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
The widest ramp is (2, 9): nums[2] = 1 <= nums[9] = 1.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems