AlgoViz

Maximum Rectangle Area with all 1's|

Hard

A histogram per row

Problem

Find the largest rectangle of all 1s in a binary matrix.

In simple words

Build a histogram of 1-heights per row and run largest-rectangle-in-histogram on each.

The idea

Turn each row into a histogram whose bar heights count consecutive 1s ending at that row, then run the largest-rectangle-in-histogram routine per row. The heights carry forward, resetting to zero on a 0.

The trick

  • Heights accumulate down the rows and reset on a 0.
  • O(rows × cols) with the monotonic-stack histogram solver.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

0
0

Step 1 of 2. Here's the example — binary matrix Values: 0.

1/2
Optimal
timeO(m*n)spaceO(n)
1for each row update heights2ans=max(ans, largestRectangleInHistogram(heights))

Input

array
[0]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

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 biggest all-1 rectangle has area 6.

Example 2

Input:
matrix = [[0,1],[1,1]]
Output:
2
Explanation:
The two right 1s form area 2.

Example 3

Input:
matrix = [[0]]
Output:
0
Explanation:
No 1s → 0.

Finished the walkthrough? Add it to your streak.