代码随想录算法训练营第五十二天|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;
    }
};
相关推荐
Frostnova丶7 小时前
【算法笔记】数学知识
笔记·算法
吴可可1237 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白9 小时前
哈希:以时间换空间的算法实战
算法
San813_LDD10 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595710 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油12 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero12 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称12 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划