[LeetCode] 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.

For example,
Given height = [2,1,5,6,2,3],
return 10.

分析:

比较难的一道题。我们构建一个stack来保存indexes。从前向后,一个一个往里推。推的时候,如果新来的一个柱形大于等于stack中顶端的柱形,那么我们就直接推;如果新来的柱形小于stack顶端的柱形,那么就稍微麻烦一点了,我们需要一直pop stack,直到顶端的柱形小于等于新的柱形。在pop的过程中,每一次pop,我们都更新一次result。这样做的结果就是:stack里的柱形永远都保持上升。每次一遇到要下降的,就更新一次前面的。还有就是,如果stack.top的柱形跟新来的柱形不是挨着的(因为之前pop过),那么top的举行永远比pop出去那些矮。

代码:(O(n))

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


想再仔细分析一下10~15行的代码。12行结束之后,我们有三个值:s.top()(简称top), temp和 i。他们之间的关系是:top < temp < i 。两两之间可以挨着也可以不挨着。如果都挨着,不用多说,因为i-top-1就是1。分析不挨着的情况:top和temp之间的柱形为什么没了呢?那是因为他们都比temp大;temp和 i 之间柱形为什么都没了呢?因为他们都比 i 大,但同时他们也比temp大,因为如果他们比temp小,那早在它们还是新来的时候,temp就应该已经被pop掉了。所以,所有空缺的位置都比temp大,所以我们有h[temp] * (i - s.top() - 1)。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值