Use the stack algorithm in the previous problem to find maximum area in every line of the matrix.
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty())
return 0;
int m=matrix.size();
int n=matrix[0].size();
vector<int> dp(n);
int res=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0)
dp[j]=matrix[i][j]-'0';
else
dp[j]=matrix[i][j]=='1'?dp[j]+1:0;
}
int area=largestRectangleArea(dp);
if(area>res)
res=area;
}
return res;
}
int largestRectangleArea(vector<int>& height) {
stack<int> s;
int res=0;
height.push_back(0);
for(int i=0;i<height.size();i++)
{
if(s.empty()||height[i]>=height[s.top()])
s.push(i);
else
{
while(!s.empty()&&height[s.top()]>height[i])
{
int h=height[s.top()];
s.pop();
int w=s.empty()?i:i-s.top()-1;
int area=h*w;
res=area>res?area:res;
}
s.push(i);
}
}
return res;
}
};