largest rectangle in histogram

Description

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.

1
2
3
4
5
6
class {
public:
int largestRectangleArea(vector<int>& heights) {
}
};

what I think

正常的思路就是遍历每一个数,对每一个数看前面和后面有没有比她小的,有则count++,没有跳出循环,利用count*height来算出结果。代码就略了。但是N^2的时间Leetcode根本不接受啊!没办法上网找一下灵感~

Advanced

堆栈http://blog.csdn.net/yutianzuijin/article/details/52072427

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class {
public:
int largestRectangleArea(vector<int> &height) {
int ret = 0;
stack<int> stk;
for(int i = 0; i < height.size(); i ++)
{
if(stk.empty() || stk.top() <= height[i])
stk.push(height[i]);
else
{
int count = 0;
while(!stk.empty() && stk.top() > height[i])
{
count ++;
ret = max(ret, stk.top()*count);
stk.pop();
}
while(count --)
stk.push(height[i]);
stk.push(height[i]);
}
}
int count = 1;
while(!stk.empty())
{
ret = max(ret, stk.top()*count);
stk.pop();
count ++;
}
return ret;
}
};