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
.
此題難度很大,個人並未想出來。第一反應是F(i,j)但是超時錯誤。此處借鑑他人。並理解了下代碼。以及相關題目Maximal Rectangle,利用此題結論。先做的Maximal Rectangle,直接被打擊,後面度娘下,發現此題很刁鑽,利用了本題的思路。否則有的超時!!
借鑑自:http://blog.csdn.net/sbitswc/article/details/33451347
int largestRectangleArea(vector<int> &height)
{
stack<int> st;
int max_area = 0;
height.push_back(0);//技巧
for(int i = 0;i < height.size();)
{
if(st.empty() || height[i] > height[st.top()])
{
st.push(i);
i++;
}
else
{
int temp_index = st.top();
st.pop();
max_area = max(max_area, height[temp_index]*(st.empty()? i:i-st.top()-1));
//cout<<height[temp_index]*(st.empty()? i:i-st.top()-1)<<endl;
//此題關鍵的地方 最後一句索引與高度的獲取。在棧裏面的是最小遞增序列(當前)
}
}
return max_area;
}