Maximum Rectangle Area with All 1s

Implement maximalRectangle

Given a binary matrix, find the largest rectangle made entirely of 1s and return its area. Checking every candidate rectangle directly works but re-examines huge overlapping regions over and over. The faster path reframes each row as a bar chart: for every column, track how many 1s have piled up consecutively ending at the current row. That single row's bar chart is exactly the "largest rectangle in a histogram" problem, solvable in one linear pass with a stack that only ever holds increasing bars — pop a bar the moment a shorter one appears, and its width is exactly how far it could have stretched as the tallest bar in its own rectangle. Running that once per row, keeping a running maximum, finds the biggest all-1s rectangle in the whole grid without ever double-checking the same region.

Example 1:

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

Output: 4

Example 2:

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

Output: 6

Example 3:

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

Output: 0

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ rows, cols ≤ 200
  • every entry of matrix is either 0 or 1

matrix =

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