力扣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;
      }
  };
相关推荐
数研小生5 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克5 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手5 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.5 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
爱看科技6 小时前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
qq_417129256 小时前
C++中的桥接模式变体
开发语言·c++·算法
Hello World . .6 小时前
数据结构:队列
c语言·开发语言·数据结构·vim
YuTaoShao6 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
吴维炜8 小时前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
Σίσυφος19009 小时前
PCL Point-to-Point ICP详解
人工智能·算法