Skip to content

Maximal Rectangle⚓︎

Link

Description⚓︎

Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Example 1:

Example

  • Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
  • Output: 6
  • Explanation: The maximal rectangle is shown in the above picture.

Example 2:

  • Input: matrix = [["0"]]
  • Output: 0

Example 3:

  • Input: matrix = [["1"]]
  • Output: 1

Constraints:

  • rows == matrix.length
  • cols == matrix[i].length
  • 1 <= row, cols <= 200
  • matrix[i][j] is '0' or '1'.

Solution⚓︎

class Solution {
private:
    // See leetcode 84: Largest Rectangle in Histogram 
    int largestRectangleArea(vector<int>& height) {
        int n = height.size();
        int res = 0;
        stack<int> stk;

        for (int i = 0; i < n; i++) {
            while (!stk.empty() && height[stk.top()] >= height[i]) {
                int current = stk.top();
                stk.pop();
                int left = !stk.empty() ? stk.top() : -1;
                res = max(res, height[current] * (i - left - 1));
            }
            stk.push(i);
        }

        while (!stk.empty()) {
            int current = stk.top();
            stk.pop();
            int left = !stk.empty() ? stk.top() : -1;
            res = max(res, height[current] * (n - left - 1));
        }

        return res;
    }

public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        vector<int> height(m, 0);
        int res = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;
            }
            res = max(largestRectangleArea(height), res);
        }

        return res;
    }
};
  • Time complexity: \(O(n\times m)\), where \(n\) is the number of rows and \(m\) is the number of columns in the matrix;
  • Space complexity: \(O(m)\), primarily due to the use of the height vector and the stack, with \(m\) being the number of columns.