Maximal Rectangle

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

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

Analysis

It's not a easy problem, yet if you've done "Largest Rectangle in Histogram", one approach is convert to that problem for each row, and get "largest rectangle in histogram" for each row, and compare each row's "largest rectangle" to get maximal rectangle in the matrix.

For example:

Original matrix[][]

[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]

convert to =>

heights[][] matrix

That for heights[i][j] it stands for, for i-th row, the height at column j, thus each row in heights[i][j] could just be input for the function int largestRectangleArea(int[] heights).

At this moment, the "Maximal Rectangle" problem has been converted to a series of "Largest Rectangle in Histogram" problem.

O(n\*m) time, O(n\*m) space

Solution

Convert to Largest Rectangle in Histogram problem (where DP is used) - 13 ms, faster than 70.66%

Convert to largest rectangle histogram (where monotonous stack is used) - (35 ms AC)

Combining largestRectangleArea function into the same loop - using stack

Another combined implementation - using Stack - (35 ms, faster than 37.38% )

Reference

Last updated

Was this helpful?