Approach

Today’s daily can be solved with the technique as mono-stack in LC-84.

First, we calculate the continuous 1 in the horizontal direction (only need to calculate one side). For instance, given

0 1 1 0 0 1 1 1

we have

0 1 2 0 0 1 2 3

denoting how many ones are there, and then we process each vertical direction as it is a histogram (as LC-84).

Code

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int>> ones(m, vector<int>(n));
        for(int i = 0 ; i < m ; ++i) {
            int cnt = 0;
            for(int j = 0 ; j < n ; ++j) {
                if(matrix[i][j] == '1') ++cnt;
                else cnt = 0;
                ones[i][j] = cnt;
            }
        }

        vector<vector<int>> left(m, vector<int>(n));
        vector<vector<int>> right(m, vector<int>(n));
        int maxRect = 0 ;
        for(int j = 0 ; j < n ; ++j) {
            vector<int> stk;
            for(int i = 0 ; i < m ; ++i) {
                while(!stk.empty() && ones[stk.back()][j] >= ones[i][j]) stk.pop_back();
                left[i][j] = stk.empty() ? -1 : stk.back();
                stk.push_back(i);
            }
            stk.clear();
            for(int i = m-1 ; i >= 0 ; --i) {
                while(!stk.empty() && ones[stk.back()][j] >= ones[i][j]) stk.pop_back();
                right[i][j] = stk.empty() ? m : stk.back();
                stk.push_back(i);
            }
            // calculate.
            for(int i = 0 ; i < m ; ++i) {
                int curRect = (right[i][j] - left[i][j] - 1) * ones[i][j];
                maxRect = max(maxRect, curRect);
            }
        }

        return maxRect;
    }
};