Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
O(m*n),a combination of the problem:LeetCode Largest Rectangle in Histogram
class Solution {
public:
int LargestRect(const vector<int>& height){
vector<int> left;
vector<int> right;
stack<int> s;
left.resize(height.size());
right.resize(height.size());
for(int i=0;i<height.size();++i){
if(height[i]==0){
s.push(i);
continue;
}
while(!s.empty()&&height[s.top()]>=height[i])
s.pop();
left[i]=s.empty()?i:(i-s.top()-1);
s.push(i);
}
s=stack<int>();
for(int i=height.size()-1;i>=0;--i){
if(height[i]==0){
s.push(i);
continue;
}
while(!s.empty()&&height[s.top()]>=height[i])
s.pop();
right[i]=s.empty()?height.size()-1-i:(s.top()-i-1);
s.push(i);
}
int area=0;
for(int i=0;i<height.size();++i){
if(height[i]>0){
area=max(area,height[i]*(left[i]+right[i]+1));
}
}
return area;
}
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(matrix.empty())
return 0;
vector<int> height;
int maxarea=0;
height.resize(matrix[0].size());
for(int i=0;i<matrix.size();++i){
for(int j=0;j<matrix[i].size();++j){
if(matrix[i][j]=='1'){
++height[j];
}else{
height[j]=0;
}
}
maxarea=max(maxarea,LargestRect(height));
}
return maxarea;
}
};