Maximum Width Ramp

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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

Examples

Example 1:

Input: nums = [6,0,8,2,1,5]

Output: 4

Explanation: The maximum width ramp is at pair (1, 5): nums[1] = 0 <= nums[5] = 5, so the width is 5 - 1 = 4.

Example 2:

Input: nums = [9,8,1,0,1,9,4,0,4,1]

Output: 7

Explanation: The maximum width ramp is at pair (2, 9): nums[2] = 1 <= nums[9] = 1, so the width is 9 - 2 = 7.

Example 3:

Input: nums = [3,2,1]

Output: 0

Explanation: No pair (i, j) exists where i < j and nums[i] <= nums[j], so the answer is 0.

Constraints

  • 2 <= nums.length <= 5 * 10⁴
  • 0 <= nums[i] <= 5 * 10⁴
Source: Monotonic Stack pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle