85. Maximal Rectangle

Hard (Khó) Python 🔗 Xem trên LeetCode

📋 Đề Bài

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

🧠 Thuật Toán & Kỹ Thuật

Stack (Ngăn xếp)Matrix (Ma trận)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

Python 0085-maximal-rectangle.py
class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        stack = [-1]
        n = len(heights)
        ans = 0
        
        for i in range(n):
            while stack[-1] != -1 and heights[stack[-1]] >= heights[i]:
                ans = max(ans, heights[stack.pop()] * (i - stack[-1] - 1))
            stack.append(i)
            
        while stack[-1] != -1:
            ans = max(ans, heights[stack.pop()] * (n - stack[-1] - 1))
        
        return ans
    
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        n, m = len(matrix), len(matrix[0])
        heights = [0 for _ in range(m)]
        ans = 0
        
        for i in range(n):
            for j in range(m):
                if matrix[i][j] == '1':
                    heights[j] += 1
                else:
                    heights[j] = 0
                    
            ans = max(ans, self.largestRectangleArea(heights))
            
        return ans