Maximum Rectangles

Stack / Queues FAQs Hard

Given a m x n binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Examples:

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 highlighted part depicts the rectangle with the largest area i.e. 6.

Input : matrix = [[1]] 

Output: 1 

Explanation: In this case, there is only one rectangle with area 1.

Input: matrix = [[1, 0, 1, 0, 0], [1, 0, 1, 1, 1]]

Constraints

  •   1<=n,m<=1000
  •   0<=matrix[i][j]<=1

Hints

  • Convert each row into a histogram For each row i, compute a heights array, where: heights[j]=heights[j]+1if matrix[i][j]=1, else 0 This transforms each row into a histogram where heights represent consecutive 1s.
  • Apply the Largest Rectangle in Histogram algorithm. Use monotonic stack to compute maximum rectangular area row-wise. Track the maximum area across all rows.

Company Tags

PwC Splunk KPMG OYO Rooms Byju's Dropbox Airbnb Databricks Epic Games Activision Blizzard NVIDIA Bain & Company GE Healthcare Etsy Reddit Ernst & Young Riot Games Chewy Roche IBM Electronic Arts Robinhood Uber Texas Instruments Walmart Google Microsoft Amazon Meta Apple Netflix Adobe