[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实现
1 |
|
[LeetCode] 962. Maximum Width Ramp
https://shurui91.github.io/posts/2923917953.html