代码随想录算法训练营第五十二天|leetcode第84题

一、leetcode第84题

本题要求柱状图中能勾勒出的最大矩形面积,使用单调栈,要求出单调栈栈顶元素左右比其小的第一个元素,因此使用递减栈,在遇到比栈顶元素小的元素时以栈顶元素为基准计算最大矩形面积。为了避免单调递减无法计算结果并且使所有元素都作为基准计算最大矩形面积,因此在数组的开头与结尾要加上元素0。

具体代码如下:

cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
    stack<int>st;
    int result=0;
    heights.insert(heights.begin(),0);
    heights.push_back(0);
    st.push(0);
    for(int i=1;i<heights.size();i++)
    {
        if(heights[i]>heights[st.top()])
        {
            st.push(i);
        }
        else if(heights[i]==heights[st.top()])
        {
            st.pop();
            st.push(i);
        }
        else
        {
            while(!st.empty()&&heights[st.top()]>heights[i])
            {
                int mid=st.top();
                st.pop();
                if(!st.empty())
                {
                    int left=st.top();
                    int right=i;
                    result=max(result,heights[mid]*(right-left-1));
                }
            }
            st.push(i);
        }
    }
    return result;
    }
};
相关推荐
飞川撸码1 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
Neil今天也要学习1 小时前
永磁同步电机参数辨识算法--IPMSM拓展卡尔曼滤波全参数辨识
单片机·嵌入式硬件·算法
yzx9910132 小时前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
亮亮爱刷题2 小时前
算法练习-回溯
算法
眼镜哥(with glasses)3 小时前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
int型码农8 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
UFIT8 小时前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面8 小时前
C++刷题:日期模拟(1)
c++·学习·算法
SHERlocked938 小时前
CPP 从 0 到 1 完成一个支持 future/promise 的 Windows 异步串口通信库
c++·算法·promise
怀旧,8 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法