Largest Rectangle in Histogram (栈)

本文详细介绍了如何通过栈数据结构解决直方图最大矩形面积问题,包括题意解释、解题思路、代码实现及具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

题解:我们用栈来保存直方图中的递增子序列,若i在栈中,则在i之前比i小的直方图的下标肯定也在栈中,在i之后只能放入比height[i]高的下标,因为后面的比它高,所以以height[i]为高的矩形面积还可能增加。
若碰到了比它高度低的直方,则我们知道它的最大矩形也就到头了,所以它的面积就是栈中上一个比它低的直方与当前要入栈的比它低的直方之间的宽度乘以它的高度。

代码如下:

class Solution {
public:
    int largestRectangleArea(vector<int>& height) {
        height.push_back(0);
        int N = height.size();
        stack<int> s;
        int maxArea = 0;

        int i = 0;
        /*栈中保持一个递增子序列*/
        while(i < N) {
            if(s.empty() || height[i] >= height[s.top()]) {
                s.push(i++);
            }
            else {
                int j = s.top();
                s.pop();
                int width = (s.empty()) ? i : i-s.top()-1;
                //若为空,表示在i之前height[j]最小
                //若不为空,则表示在s.top()与i之间height[j]最小
                maxArea = max(maxArea, height[j]*width);
            }
        }
        return maxArea;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值