⚡Flashcard Drill➔
NeetCode #370LC-962MediumStack
← Back to All Problems

#370 · #962 · Maximum Width Ramp(最大宽度坡)

📌 Problem Statement & Constraints

A ramp is a pair (i, j) with i < j and nums[i] <= nums[j]. The width is j - i. Given an array nums, return the maximum width of a ramp, or 0 if none exists. Constraints: 2 <= nums.length <= 5 * 10^4, 0 <= nums[i] <= 5 * 10^4.

💡 Core Algorithmic Approaches

  1. Build a decreasing stack of indices from the left: only indices whose value is smaller than every value seen so far can be the left end of an optimal ramp.
  2. Then scan from the right. For each j, pop stack entries while nums[stack[-1]] <= nums[j] and record j - index as a candidate width.
  3. Popping is safe because the popped indices are smaller than j, and later right ends are even further away -- but they are to the left, so a smaller index can never beat the current width for those.
  4. The total work is O(n).

💻 Benchmark Python3 Implementation

class Solution:
    def maxWidthRamp(self, nums: List[int]) -> int:
        n = len(nums)
        st = []
        for i in range(n):
            # keep only indices that are strictly smaller than all previous ones
            if not st or nums[st[-1]] > nums[i]:
                st.append(i)
        best = 0
        for j in range(n - 1, -1, -1):
            while st and nums[st[-1]] <= nums[j]:
                best = max(best, j - st.pop())   # widest ramp for this left end
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each index is pushed once and popped at most once.
💾 Space Complexity
O(n) for the stack.

⚠️ Interview Pitfalls & Follow-ups

  • Pushing every index: the stack must be strictly decreasing in value, otherwise the scan from the right does not work.
  • Scanning from the left instead of the right: the width is maximised by the largest j, so the right-to-left scan is what makes the greedy correct.
  • Using >= when building the stack: equal values should not be pushed, since the earlier index is always at least as good.
  • Trying a nested loop: O(n^2).
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

最大宽度坡

给定一个整数数组 A, 坡 是元组 (i, j) ,其中 i &lt; j 且 A[i] &lt;= A[j] 。这样的坡的宽度为 j − i 。找出 A 中的坡的 最大宽度 。如果不存在坡,返回 0。约束:2 ≤ nums.length ≤ 5 × 10^4;0 ≤ nums[i] ≤ 5 × 10^4。

核心要点

  • 单调递减栈 + 逆序扫描(标准解) :① 从左到右构建一个 单调递减 的栈,只把「比当前栈顶更小」的元素下标压入——这些是潜在的左端点候选。
  • ② 从右往左扫描 :对每个 j,不断检查栈顶下标 i 是否满足 A[i] &lt;= A[j] ;若满足,则 j − i 是一个候选答案,弹出栈顶(因为更靠右的 j 已被用过,更小的 i 只可能给出更小的宽度)。
  • 为什么栈只存「递减」的下标 :若下标 i1 &lt; i2 且 A[i1] &lt;= A[i2] ,则 i2 永远不可能是最优左端点(i1 更靠左且值更小,更优)。
  • 复杂度 :O(n) 时间、O(n) 空间。

常见陷阱

  • 构建栈时用 &lt;= :会把相等的元素也压入栈,导致栈不再严格递减,虽不影响正确性但会降低效率。用 &lt; 更紧凑。
  • 从右往左扫描时忘记弹出栈顶 :会导致重复计算,且无法保证 O(n)。弹出是必须的——更靠右的 j 已经用过了。
  • 用双重循环枚举所有 (i, j) :O(n²) 在 n = 5 × 10^4 时必然超时。
  • 排序后处理 :排序会丢失下标信息(需要额外记录原下标),且逻辑更复杂。

参考实现

class Solution:
    def maxWidthRamp(self, nums: list[int]) -> int:
        n = len(nums)
        stack = []
        # ① 构建单调递减栈(只存比栈顶更小的元素下标)
        for i in range(n):
            if not stack or nums[i] < nums[stack[-1]]:
                stack.append(i)

        # ② 从右往左扫描,寻找最宽的坡
        best = 0
        for j in range(n - 1, -1, -1):
            while stack and nums[stack[-1]] <= nums[j]:
                i = stack.pop()
                if j - i > best:
                    best = j - i
        return best