Leetcode 84. Largest Rectangle in Histogram

Problem:

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

 

Solution:

  对于这个问题,我们可以用栈来做,用到栈的题目一般是维护一个递增栈和递减栈(当然只是一般来说,也会有例外),通常情况下,栈中尽量存储数组的索引,因为索引存储的信息比单纯的数值要多。当然这都是经验之谈,对于这道题而言,我们维护一个递增栈,每次推出栈中元素时计算面积,这篇博客讲的非常详细了,我就不做过多阐述了。这里主要谈一个细节,也是当时困惑我的一个问题,也就是第12行,为什么在i-stk.top()-1到i之间不存在比heights[top]更小的数了,如果存在更小的数字的话,这个长方形就形成不了了,原因是如果说存在更小的数的话,那这个数必然在之前就推入栈中了,换句话说,对于栈中的每个元素t,在遍历到i之前,所有比heights[t]小的元素都在t之前,不存在索引x大于t且比heights[x]比heights[t]小的元素x(细细体会这句话)

Code:

 

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& heights) {
 4         heights.push_back(0);
 5         stack<int> stk;
 6         int result = 0;
 7         for(int i = 0;i != heights.size();++i){
 8             while(!stk.empty() && heights[i] <= heights[stk.top()]){
 9                 int top = stk.top();
10                 stk.pop();
11                 if(!stk.empty())
12                     result = max(result,(i-stk.top()-1)*heights[top]);
13                 else
14                     result = max(result,i*heights[top]);
15             }
16             stk.push(i);
17         }
18         return result;
19     }
20 };

 

转载于:https://www.cnblogs.com/haoweizh/p/10253509.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值