LeetCode 题解工作台
最大宽度坡
给定一个整数数组 A , 坡 是元组 (i, j) ,其中 i 且 A[i] 。这样的坡的宽度为 j - i 。 找出 A 中的坡的最大宽度,如果不存在,返回 0 。 示例 1: 输入: [6,0,8,2,1,5] 输出: 4 解释: 最大宽度的坡为 (i, j) = (1, 5): A[1] = …
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
根据题意,我们可以发现,所有可能的 所构成的子序列一定是单调递减的。为什么呢?我们不妨用反证法证明一下。 假设存在 ,并且 ,那么实际上 一定不可能是一个候选值,因为 更靠左,会是一个更优的值。因此 所构成的子序列一定单调递减,并且 一定是从 0 开始。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个整数数组 A,坡是元组 (i, j),其中 i < j 且 A[i] <= A[j]。这样的坡的宽度为 j - i。
找出 A 中的坡的最大宽度,如果不存在,返回 0 。
示例 1:
输入:[6,0,8,2,1,5] 输出:4 解释: 最大宽度的坡为 (i, j) = (1, 5): A[1] = 0 且 A[5] = 5.
示例 2:
输入:[9,8,1,0,1,9,4,0,4,1] 输出:7 解释: 最大宽度的坡为 (i, j) = (2, 9): A[2] = 1 且 A[9] = 1.
提示:
2 <= A.length <= 500000 <= A[i] <= 50000
解题思路
方法一:单调栈
根据题意,我们可以发现,所有可能的 所构成的子序列一定是单调递减的。为什么呢?我们不妨用反证法证明一下。
假设存在 ,并且 ,那么实际上 一定不可能是一个候选值,因为 更靠左,会是一个更优的值。因此 所构成的子序列一定单调递减,并且 一定是从 0 开始。
我们用一个从栈底到栈顶单调递减的栈 来存储所有可能的 ,然后我们从右边界开始遍历 ,若遇到 ,说明此时构成一个坡,循环弹出栈顶元素,更新 。
时间复杂度 ,空间复杂度 ,其中 表示 的长度。
class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
stk = []
for i, v in enumerate(nums):
if not stk or nums[stk[-1]] > v:
stk.append(i)
ans = 0
for i in range(len(nums) - 1, -1, -1):
while stk and nums[stk[-1]] <= nums[i]:
ans = max(ans, i - stk.pop())
if not stk:
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate understands the two-pointer technique for optimizing problems like this one.
- question_mark
Look for clarity in the candidate's explanation of the monotonic stack's role in solving the problem.
- question_mark
Assess how well the candidate relates the problem to patterns like invariant tracking and ramp-width maximization.
常见陷阱
外企场景- error
Failing to use the monotonic stack efficiently, leading to incorrect ramp width calculations.
- error
Not recognizing that the two-pointer technique must be combined with a stack for optimal performance.
- error
Overcomplicating the problem by using a brute-force approach that results in O(n^2) time complexity.
进阶变体
外企场景- arrow_right_alt
Consider variations where the ramp definition might change, such as requiring nums[i] > nums[j] or other constraints on the array.
- arrow_right_alt
Explore edge cases with minimum and maximum array sizes to ensure the algorithm handles these scenarios effectively.
- arrow_right_alt
Consider extending the problem to allow ramps in multidimensional arrays or with additional constraints.