matrix is a grid of rows rows and cols columns. Each cell holds the string "0" or "1". Find the largest rectangle made only of "1" cells, with its sides along the grid lines, and return its area: the number of cells in it.
The rectangle can have any width and height. It does not have to be a square.
The second and third rows are "1" across their first four columns: a rectangle 2 tall and 4 wide, area 8. The block in the last three rows of the third and fourth columns is taller, but only 6 cells, and no 3 × 3 square fits anywhere.
With no "1" there is no rectangle.
A single column only holds rectangles one cell wide. The two "1"s at the top are the longest unbroken run.
Constraints
rows == matrix.lengthcols == matrix[i].length1 <= rows, cols <= 200matrix[i][j] is "0" or "1".Fix the bottom row of the rectangle. For each column, count the "1"s standing in an unbroken run upward from that row. Those counts form a bar chart.
A rectangle is fixed by its top row, bottom row, left column and right column. A 200 × 200 grid has 20100 ways to pick the two rows and 20100 ways to pick the two columns, so about 4 · 10⁸ rectangles. Checking each one cell by cell is hopeless, and even a constant-time check per rectangle is far too much.
Time O(rows · cols)Space O(cols)
The full walkthrough and code are part of Premium
8