题目描述
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.
算法思路:
请参考:https://blog.csdn.net/u012534831/article/details/74356851
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int n=static_cast<int>(height.size());
if(n<=0) return 0;
int ans=0,num;
stack<int>st;
st.push(-1);
for(int i=0;i<n;++i)
{
while(st.top()!=-1&&height[i]<height[st.top()])
{
num=st.top();
st.pop();
ans=max(ans,(i-st.top()-1)*height[num]);
}
st.push(i);
}
while(st.top()!=-1)
{
num=st.top();
st.pop();
ans=max(ans,(n-st.top()-1)*height[num]);
}
return ans;
}
};
相同算法拓展:
题目描述
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
分别遍历每一行,将每次遍历的行及以上部分看做直方图求最大面积,最后遍历所有结果,求最大值。
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int m=matrix.size();
if(m<=0) return 0;
int n=matrix[0].size();
vector<int>h(n);
fill(h.begin(),h.end(),0);
int num;
int ans=0;
stack<int>st;
st.push(-1);
for(int i=0;i<m;++i)
{
for(int j=0;j<n;++j)
{
if(matrix[i][j]=='1')
++h[j];
else
h[j]=0;
}
for(int j=0;j<n;++j)
{
while(st.top()!=-1&&h[j]<h[st.top()])
{
num=st.top();
st.pop();
ans=max(ans,(j-1-st.top())*h[num]);
}
st.push(j);
}
while(st.top()!=-1)
{
num=st.top();
st.pop();
ans=max(ans,(n-1-st.top())*h[num]);
}
}
return ans;
}
};