84. Largest Rectangle in Histogram Hard

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.


思路:本体最直接的想法就是遍历每一种情况,通过比较来获得矩形的最大值。如何更快地获得各种情况,我们先从特殊情况考虑,假设所有的方阵高度是递增的,那么我们只需要考虑每一个方阵到最右端方阵所形成的矩形大小就可以了。我们就构造一种递增的序列来求得以每一个方阵为高的矩形面积。

网上有人想到了使用栈的方式。将高较小的均放入栈中,一旦遇见高大的,就出栈并按照递增方式的面积求法得到一个面积,取最大值,将我们现在正在比较的方阵入栈,注意入栈时应该是出栈了多少个就该入栈几次正在比较的方阵,这样是为了自求面积是获得以此方阵为高的矩形的最大面积。


class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int area = 0;
        stack<int>temp;
        for (int i = 0; i < heights.size(); i++) {
            if (temp.empty() || temp.top() <= heights[i]) {
                temp.push(heights[i]);
            } else {
                int k = 0;
                while (!temp.empty() && temp.top() > heights[i]) {
                    k++;
                    area = max(area, temp.top() * k);
                    temp.pop();
                }
                while (k--) {
                    temp.push(heights[i]);
                }
                temp.push(heights[i]);
            }
        }
        int k = 1;
        while (!temp.empty()) {
            area = max(area, temp.top() * k);
            k++;
            temp.pop();
        }
        return area;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值