962.js
/** ------------------------------------------------------------------------------
*
* 962. Maximum Width Ramp
* Topics: Stack
* https://leetcode.com/problems/maximum-width-ramp/description/?envType=daily-question&envId=2024-10-10
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @return {number}
*/
var maxWidthRamp = function (nums) {
let ramp = Number.MIN_SAFE_INTEGER
let stack = []
for (let i = 0; i < nums.length; i += 1) {
while (stack.length === 0 || nums[stack.length - 1] > nums[i]) {
stack.push(i)
}
}
for (let i = nums.length - 1; i >= 0; i -= 1) {
while (stack.length > 0 && nums[i] >= nums[stack.length - 1]) {
const index = stack.pop()
ramp = Math.max(ramp, i - index)
}
}
return ramp
}