Stacks and Queues Monotonic stack
219. Maximal Rectangle
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
Input: matrix = [[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 0]]
9Explanation: 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
Input: matrix = [[1], [1], [0], [1], [1], [1]]
3Explanation: 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
Input: matrix = [[0, 0, 0], [0, 0, 0]]
0Explanation: 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.
Constraints
m == matrix.length,n == matrix[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 105matrix[i][j]is 0 or 1.
Clarifying questions
What you would ask an interviewer before writing any code.