力扣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;
      }
  };
相关推荐
im_AMBER5 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹6 小时前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD6 小时前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法
苏小瀚6 小时前
[算法]---路径问题
数据结构·算法·leetcode
月明长歌7 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir7 小时前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法
t198751287 小时前
MATLAB水声信道仿真程序
开发语言·算法·matlab
前端之虎陈随易7 小时前
MoonBit内置数据结构详解
数据结构·数据库·redis
CoderYanger8 小时前
动态规划算法-简单多状态dp问题:15.买卖股票的最佳时机含冷冻期
开发语言·算法·leetcode·动态规划·1024程序员节
Xの哲學8 小时前
Linux RTC深度剖析:从硬件原理到驱动实践
linux·服务器·算法·架构·边缘计算