力扣962.最大宽度坡

力扣962.最大宽度坡

  • 单调栈

    • 栈中存从nums0开始的一个单调下降 的序列
      • 为了让坡的底尽量小
    • 然后倒序遍历nums,找符合条件的栈中元素 弹出
cpp 复制代码
  class Solution {
  public:
      int maxWidthRamp(vector<int>& nums) {
          int n = nums.size();
          int res = 0;
          stack<int> st;
          for(int i=0;i<n;i++)
              if(st.empty() || nums[st.top()] > nums[i])
                  st.emplace(i);
          for(int i=n-1;i>=0;i--)
          {
              while(!st.empty() && nums[st.top()] <= nums[i])
              {
                  int t = st.top();
                  st.pop();
                  res = max(res,i - t);
              }
          }
          return res;
      }
  };

参考题解:https://leetcode.cn/problems/maximum-width-ramp/solutions/666604/zui-da-kuan-du-po-dan-diao-zhan-cun-de-s-myj9/

相关推荐
Keven_117 分钟前
算法札记:有限差分
算法
忙里偷闲学python10 分钟前
GK2A 林火蔓延预报算法说明
算法
我是伪码农19 分钟前
11.21程序设计
数据结构·算法
Tisfy1 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦2 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法
Shaoshing3 小时前
LeetCode100 155.最小栈
java·数据结构·算法
秋天的怀念_David3 小时前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 2293 小时前
C++ 算法模板与错题 (差分)
开发语言·c++·算法