class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { int m = matrix.size(); if (m == 0) return 0; int n = matrix[0].size(); if (n == 0) return 0; vector<vector<int>> v(m, vector<int>(n, 0)); for (int j = 0; j < n; j++) v[0][j] = matrix[0][j] == '1'; for (int i = 1; i < m; i++) for (int j = 0; j < n; j++) { if (matrix[i][j] == '1') v[i][j] = v[i-1][j] + 1; } int res = 0; for (int i = 0; i < m; i++) res = max(res, helper(v, i)); return res; } int helper(vector<vector<int>>& v, int i) { vector<int>& ln = v[i]; ln.push_back(0); stack<int> s; int res = 0; for (int j = 0; j < ln.size(); j++) { while (!s.empty() && ln[j] < ln[s.top()]) { int t = s.top(); s.pop(); int w = s.empty() ? j : (j - s.top() - 1); res = max(res, ln[t] * w); } s.push(j); } return res; } };