imashutosh51

Maximum rectangle containing 1 in binary matrix

Jul 23rd, 2022 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. '''
  2. Logic:
  3. If we consider each row as a base and then find the maximum reactangle in histogram then you will get the maximum
  4. rectange from the binary matrix.
  5. '''
  6. from typing import List
  7.  
  8. def largest_rectangle(arr):
  9.     st = []
  10.     st.append((0, -1))  # (index, prev_smaller_index)
  11.     ans = float('-inf')
  12.     n = len(arr)
  13.    
  14.     for i in range(1, n):
  15.         while st and arr[st[-1][0]] >= arr[i]:
  16.             idx, prev = st.pop()
  17.             ans = max(ans, (i - prev - 1) * arr[idx])
  18.        
  19.         if not st:
  20.             st.append((i, -1))
  21.         else:
  22.             st.append((i, st[-1][0]))
  23.    
  24.     while st:
  25.         idx, prev = st.pop()
  26.         ans = max(ans, (n - prev - 1) * arr[idx])
  27.    
  28.     return ans
  29.  
  30.  
  31. class Solution:
  32.     def maximalRectangle(self, matrix: List[List[str]]) -> int:
  33.         if not matrix:
  34.             return 0
  35.        
  36.         n, m = len(matrix), len(matrix[0])
  37.        
  38.         # convert to int
  39.         matrix = [[int(x) for x in row] for row in matrix]
  40.        
  41.         ans = float('-inf')
  42.        
  43.         for i in range(n):
  44.             if i != 0:
  45.                 for j in range(m):
  46.                     if matrix[i][j] != 0:
  47.                         matrix[i][j] += matrix[i - 1][j]
  48.                     else:
  49.                         matrix[i][j] = 0
  50.            
  51.             ans = max(ans, largest_rectangle(matrix[i]))
  52.        
  53.         return ans if ans != float('-inf') else 0
Advertisement
Add Comment
Please, Sign In to add comment