力扣84.柱状图中最大的矩形

力扣84.柱状图中最大的矩形

  • 初始化pre_max 为-1 存距离最近的小于hi的元素下标

  • 初始化suf_max 为 n 存距离最近的小于hi的元素下标

cpp 复制代码
  class Solution {
  public:
      int largestRectangleArea(vector<int>& heights) {
          int n = heights.size();
          //分别初始化-1 和 n
          vector<int> pre_max(n,-1),suf_max(n,n);
          stack<int> st;
          for(int i=0;i<n;i++)
          {
              while(!st.empty() && heights[i] <= heights[st.top()]) st.pop();
              if(!st.empty()) pre_max[i] = st.top();
              st.push(i);
          }
          
          st = stack<int>();
          for(int i=n-1;i>=0;i--)
          {
              while(!st.empty() && heights[i] <= heights[st.top()]) st.pop();
              if(!st.empty()) suf_max[i] = st.top();
              st.push(i);
          }
      
          int res=0;
          for(int i=0;i<n;i++)
          {
              res = max(res,(suf_max[i] - pre_max[i] - 1) * heights[i]);
          }
          return res;
      }
  };
相关推荐
晴天的雨.99239 分钟前
[C++算法]快乐数
数据结构·c++·算法
孤狼warrior43 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
影视飓风TIM1 小时前
C++11 核心新特性完整梳理
数据结构·c++·算法
晴天的雨.9921 小时前
[C++]算法双指针 复写0
数据结构·c++·算法
橘子汽水1681 小时前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
圣保罗的大教堂1 小时前
leetcode 1140. 石子游戏 II 中等
leetcode
mmmmath_31 小时前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil2081 小时前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z1 小时前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode