力扣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;
      }
  };
相关推荐
haoly19892 小时前
数据结构和算法篇-线性查找优化-移至开头策略
数据结构·算法·移至开头策略
学Linux的语莫5 小时前
机器学习数据处理
java·算法·机器学习
earthzhang20215 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
2301_803554527 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
sali-tec8 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
SandySY8 小时前
品三国谈人性
算法·架构
小欣加油9 小时前
leetcode 62 不同路径
c++·算法·leetcode·职场和发展
夏鹏今天学习了吗9 小时前
【LeetCode热题100(38/100)】翻转二叉树
算法·leetcode·职场和发展
夏鹏今天学习了吗9 小时前
【LeetCode热题100(36/100)】二叉树的中序遍历
算法·leetcode·职场和发展
DTS小夏9 小时前
算法社Python基础入门面试题库(新手版·含答案)
python·算法·面试