[LeetCode] 962. Maximum Width Ramp
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.
Example 1:
Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
Example 2:
Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
Constraints:
2 <= nums.length <= 5 * 104
0 <= nums[i] <= 5 * 104
最大宽度坡。
给定一个整数数组 A,坡是元组 (i, j),其中 i < j 且 A[i] <= A[j]。这样的坡的宽度为 j - i。找出 A 中的坡的最大宽度,如果不存在,返回 0 。
思路
这道题的思路是单调栈,不过这道题跟一般的单调栈题目有些不同。这道题的单调栈找的是两个距离最远的下标。其余思路参见代码注释。
复杂度
时间O(n)
空间O(n)
代码
Java实现
class Solution {
public int maxWidthRamp(int[] nums) {
Deque<Integer> stack = new ArrayDeque<>();
int n = nums.length;
int res = 0;
// 入栈的元素越来越小
for (int i = 0; i < n; i++) {
if (stack.isEmpty() || nums[i] < nums[stack.peekLast()]) {
stack.offerLast(i);
}
}
// 从右往左扫描,把当前元素当做 j,栈顶元素当做 i,计算宽度
// 如果当前元素 >= 栈顶元素,则记录两者的差值,并弹出栈顶元素
for (int j = n - 1; j > 0; j--) {
while (!stack.isEmpty() && nums[j] >= nums[stack.peekLast()]) {
res = Math.max(res, j - stack.pollLast());
}
}
return res;
}
}