Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
1 0 1 0 0
2 0 2 1 1
3 1 3 2 2
4 0 0 3 0
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int row = matrix.size();
if(row == 0) return 0;
int col = matrix[0].size();
int res = 0;
vector<vector<int>> dp(row, vector<int>(col, 0));
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(i > 0) dp[i][j] = (matrix[i][j]-'0') * (dp[i-1][j] + (matrix[i][j]-'0'));
else dp[i][j] = matrix[i][j]-'0';
}
}
for(int i = 0; i < row; i++){
res = max(res, largestRectangleArea(dp[i]));
}
return res;
}
private:
int largestRectangleArea(vector<int>& heights) {
stack<int> stk;
heights.push_back(0);
int res = 0;
for (int i = 0; i < heights.size(); i++){
if(stk.empty() || heights[i] > heights[stk.top()]){
stk.push(i);
}else{
int h = stk.top();
stk.pop();
res = max(res, (stk.empty()?i:i-stk.top()-1) * heights[h]);
i--;
}
}
return res;
}
};