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

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

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

  • 初始化suf_max 为 n 存距离最近的小于h[i]的元素下标

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;
      }
  };
相关推荐
卡卡_R-Python1 小时前
简单线性回归分析-基于R语言
算法·r语言·线性回归
半聋半瞎1 小时前
【顺序表使用练习】发牌游戏
java·数据结构·游戏
luthane1 小时前
python 实现lstm prediction预测算法
python·算法·lstm
失败才是人生常态1 小时前
LeetCode热题100速通
算法·leetcode·职场和发展
Cosmoshhhyyy1 小时前
LeetCode:1845. 座位预约管理系统(优先级队列 Java)
java·算法·leetcode
xxxmmc1 小时前
Leetcode 680 Valid Palidrone II
leetcode
hn小菜鸡1 小时前
LeetCode 面试经典150题 50.Pow(x,n)
算法·leetcode·面试
逃课当码农2 小时前
链表的基础知识
数据结构·链表
Reese_Cool2 小时前
【数据结构与算法】算法和算法分析
android·c语言·数据结构·算法
白葵新2 小时前
PCL 移除点云边缘不连续的点
c++·算法·计算机视觉·3d