代码随想录算法训练营第五十二天|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;
    }
};
相关推荐
敲敲了个代码4 小时前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·javascript·vue.js·学习·面试·职场和发展·前端框架
wadesir5 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878386 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill6 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit6 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung6 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
七禾页丫6 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken7 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊7 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino7 小时前
agc011_e 题解
算法