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 =
For example,10
unit.Given height =
[2,1,5,6,2,3]
,return
10
.思路:这题太tricky了,看了别人的code还不懂,跑了几个test cases才明白的:(
from luckynoob: http://www.mitbbs.com/article/JobHunting/32272665_0.html
int largestRectArea(vector<int> &h) {
stack<int> p;
int i = 0, m = 0;
h.push_back(0);
while(i < h.size()) {
if(p.empty() || h[p.top()] <= h[i])
p.push(i++);
else {
int t = p.top();
p.pop();
m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 ));
}
}
return m;
}
sweet
ReplyDelete