LeetCode 85. 最大矩形 Python

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

思路:遍历每一行,在垂直放下进行相加,变成一维数组,利用84题的解法进行求解最大值

Python:

class Solution:
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        n = len(matrix)
        if n == 0:
            return 0
        m = len(matrix[0])
        h = [0] * (m+1)
        self.ans = 0
        
        
        for i in range(n):
            for j in range(m):
                if matrix[i][j] == '1':
                    h[j] += 1
                else:
                    h[j] = 0
            self.ans = self.robot(self.ans,h)
        return self.ans
    
    def robot(self,maxL,h):
        stk = []
        m = len(h) - 1
        i = 0
        while i <= m:
            if len(stk) == 0 or h[stk[-1]] < h[i]:
                stk.append(i)
                i += 1
            else:
                now_idx = stk.pop()
                if len(stk) == 0:
                    maxL = max(maxL,i * h[now_idx])
                else:
                    maxL = max(maxL,(i - stk[-1] - 1) * h[now_idx])
        return maxL

 

你可能感兴趣的:(LeetCode 85. 最大矩形 Python)