本文最后更新于 354 天前,如有失效请评论区留言。
单调栈我的痛点,不像模板类那样直接套用即可,更多地像贪心一样捉摸不定。
求最短
https://leetcode.cn/problems/next-greater-element-i/description/
class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        idx = {x: i for i, x in enumerate(nums1)}
        ans = [-1] * len(nums1)
        st = []
        for x in reversed(nums2):
            while st and x >= st[-1]:
                # 由于 x 的出现,栈顶元素永远不会是左边元素的「下一个更大元素」
                st.pop()
            if st and x in idx:  # x 在 nums1 中
                ans[idx[x]] = st[-1]  # 记录答案
            st.append(x)
        return ans求最长
https://leetcode.cn/problems/maximum-width-ramp/
class Solution:
    def maxWidthRamp(self, nums: List[int]) -> int:
        n = len(nums)
        st = []
        for j, x in enumerate(nums):
            if not st or x < nums[st[-1]]:
                st.append(j)
        ans = 0
        for i in range(n - 1, 0, -1):
            while st and nums[i] >= nums[st[-1]]:
                ans = max(ans, i - st.pop())  # [st[-1],i) 可能是最长子数组
        return ans
