oneby7

Stacks and Queues Monotonic stack

219. Maximal Rectangle

Hard

You are given a grid matrix with m rows and n columns, in which every cell holds 0 or 1. Return the area of the largest rectangle that holds only 1s.

The rectangle's sides run along the grid lines, so it covers whole cells: a run of neighbouring rows and, in each of them, the same run of neighbouring columns. Its area is the number of cells it covers. A single cell that holds 1 is a rectangle of area 1. If the grid holds no 1, return 0.

Example 1

10111111110111011110

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

Output: 9

Explanation: Rows 1 to 3 hold 1s in columns 1 to 3, a block of 3 × 3 = 9 cells. Columns 2 and 3 run down all four rows but make only 4 × 2 = 8, and row 1 on its own makes 5.

Example 2

110111

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

Output: 3

Explanation: The grid is one column wide. The 0 in row 2 splits the 1s, so the best rectangle is the three 1s below it.

Example 3

000000

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

Output: 0

Explanation: There is no 1, so no rectangle of 1s exists.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[1, 1, 0], [1, 1, 1], [0, 1, 1]]

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • matrix[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.