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 =10unit.
For example,
Given height =[2,1,5,6,2,3],
return10
自己的理解在笔记本里,先贴上代码
int largestRectangleArea(vector<int> &height) {
if (height.empty())
return 0;
int maxArea(0);
stack<int> st;
int i(0);
int len = height.size();
while (i<len)
{
if (st.empty()||height[i]>=height[st.top()])
{
st.push(i);
++i;
}
else
{
int ntop = height[st.top()];
st.pop();
int Area = ntop*(st.empty() ? i : (i - st.top() - 1));
maxArea = max(Area, maxArea);
}
}
while (!st.empty())
{
int ntop = height[st.top()];
st.pop();
int Area = ntop*(st.empty() ? i : (i - st.top() - 1));
maxArea = max(Area, maxArea);
}
return maxArea;
}