代码随想录算法训练营第五十二天|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 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望1 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng1 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88892 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
偷偷的卷2 小时前
【算法笔记 11】贪心策略六
笔记·算法
ZPC82102 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
_w_z_j_3 小时前
爱丽丝的人偶
算法
老前端的功夫3 小时前
Vue2中key的深度解析:Diff算法的性能优化之道
前端·javascript·vue.js·算法·性能优化
想要打 Acm 的小周同学呀4 小时前
爬虫相关的面试问题
爬虫·selenium·职场和发展
yongui478344 小时前
基于深度随机森林(Deep Forest)的分类算法实现
算法·随机森林·分类