代码随想录算法训练营第五十二天|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;
    }
};
相关推荐
Aczone2842 分钟前
硬件(六)arm指令
开发语言·汇编·arm开发·嵌入式硬件·算法
luckys.one5 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|7 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师7 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo37 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC8 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle9 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx11 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐12 小时前
算法之常见八大排序
数据结构·算法·排序算法