Skip to content
Problem 85 · LeetCode 85(opens in a new tab)

Maximal Rectangle

HardDynamic programming

You get a grid matrix of rows × cols cells, each holding the character "0" or "1". Find the rectangle with the largest area that is made only of 1 cells, with sides along the grid lines.

Return that area, the number of cells inside it. If the grid has no 1 at all, return 0.

Example 1

Input:  matrix = [["0","1","1"],["1","1","1"]]
Output: 4
Why:    columns 1 and 2 of both rows form a 2 × 2 block of 1s
2 more examples and the constraints

Example 2

Input:  matrix = [["0","0"],["0","0"]]
Output: 0
Why:    there is no 1 to build on

Example 3

Input:  matrix = [["1","1","0","1"]]
Output: 2
Why:    the first two cells; the 0 cuts the row

Constraints

  • 1 ≤ rows, cols ≤ 200
  • Every cell is "0" or "1"

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Run widths, grown upwardO(rows² · cols)
  2. Histogram per row, monotonic stackO(rows · cols)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 200 × 200 grid of 1sVerdict
Run widths, grown upwardO(rows² · cols)
Passes; simple to explain
Histogram per row, monotonic stackO(rows · cols)
Best; linear in the grid

rows and cols are the grid's height and width.

Edge cases to test

  • No 1s. A grid of 0s has no rectangle, so the answer is 0.
  • A single row or column. The answer is the longest unbroken run of 1s.
  • All 1s. The whole grid is the rectangle: rows × cols.
  • Tall beats wide. A narrow column of four 1s (area 4) can beat a wider block of two rows; check every height, not just the widest run.

Common mistakes

  • Comparing cells with the number 1 instead of the character "1".
  • Forgetting to reset heights[c] to 0 on a 0 cell, so bars float over gaps.
  • Leaving bars on the stack at the end of a row instead of flushing them with a final 0.

How to talk through it

  1. 1Clarify. Are cells characters or numbers? Can the grid be empty? Is a single cell a rectangle?
  2. 2Start simple. Run widths per cell, then grow each rectangle upward: O(rows² · cols).
  3. 3Spot the histogram. Every row is the floor of a histogram of 1-runs, so the task becomes largest rectangle in a histogram, once per row.
  4. 4Use the stack. A stack of rising heights gives each bar's full width when it is popped, in O(cols) per row.
  5. 5Test out loud. Run a grid of 0s, a single row, an all-1s grid and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?