Skip to content

85. Maximal Rectangle

Array Dynamic Programming Stack Matrix Monotonic Stack

Problem - Maximal Rectangle

Hard

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:

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 <= rows, cols <= 200
  • matrix[i][j] is '0' or '1'.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        heights = [0] * len(matrix[0])
        result = 0
        for row in matrix:
            for j, val in enumerate(row):
                if val == "1":
                    heights[j] += 1
                else:
                    heights[j] = 0
            result = max(result, self.lgstRecArea(heights))
        return result

    def lgstRecArea(self, heights : List[int]) -> int:
        n = len(heights)
        stk = []
        left, right = [-1] * n, [n] * n

        for i, h in enumerate(heights):
            while stk and heights[stk[-1]] >= h:
                stk.pop()
            if stk:
                left[i] = stk[-1]
            stk.append(i)

        stk = []
        for i in range(n - 1, -1, -1):
            h = heights[i]
            while stk and heights[stk[-1]] >= h:
                stk.pop()
            if stk:
                right[i] = stk[-1]
            stk.append(i)
        return max((right[i] - left[i] - 1) * h for i, h in enumerate(heights))

Submission Stats:

  • Runtime: 35 ms (69.63%)
  • Memory: 24.5 MB (8.87%)