SDE & MLE Prep

85. Maximal Rectangle

Problem

Given a binary matrix of '0'/'1' characters, return the area of the largest rectangle containing only '1's.

Example: ["10100","10111","11111","10010"] → 6

Constraints: up to 200 × 200.

Treat each row as the floor of a histogram: h[c] = consecutive 1s ending at this row. Run Largest Rectangle in Histogram on every row.

row 0  1 0 1 0 0      h = 1 0 1 0 0
row 1  1 0 1 1 1      h = 2 0 2 1 1
row 2  1 1 1 1 1      h = 3 1 3 2 2   -> histogram max 6

Complexity: O(rows × cols).

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0
        h = [0] * len(matrix[0])
        best = 0
        for row in matrix:
            for c, v in enumerate(row):
                h[c] = h[c] + 1 if v == "1" else 0
            st = []
            for i, x in enumerate(h + [0]):
                while st and h[st[-1]] >= x:
                    top = h[st.pop()]
                    best = max(best, top * (i - (st[-1] if st else -1) - 1))
                st.append(i)
        return best