LeetCode 题解:84. Largest Rectangle in Histogram

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.
在这里插入图片描述
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
在这里插入图片描述
The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:
Input: [2,1,5,6,2,3]
Output: 10

解题思路

这道题使用栈作为数据结构记录遍历过的坐标位置
算法主要分为两种情况:

  1. 如果当前位置 i 所对应的 heights[i] 大于栈顶记录的 heights[stack.top()],那么将当前位置入栈
  2. 否则,从栈顶元素开始,计算所能得到的最大矩形面积。由于栈中保存的是一个递增序列,那么对于每一个栈中记录的位置 stack[p],它的面积就是它对应的高度( heights[stack[p]] )和它所跨越的数组区间的宽度(它的前一个元素( stack[p-1])与当前位置 i 之间的距离 - 1)的乘积。比较最大面积 result 与当前计算得出的面积,取二者的较大值。重复上述操作,直到满足(1)中的条件。

C++代码

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int res = 0, count = 0;
        stack<int> rec;
        heights.push_back(0);
        for(int i = 0; i < heights.size(); ) {
            if(rec.empty() || heights[rec.top()] <= heights[i]) {
                rec.push(i);
                i++;
            }
            else {
                count = rec.top();
                rec.pop();
                res = max(res, heights[count] * (rec.empty()? i : i - rec.top() - 1));
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值