Skip to content
BytePatterns

Largest All-Ones Rectangle

HardMatrix & Grid#monotonic-stack#grid-scan~45m

Problem

A grid of rows and columns holds only 0s and 1s. Find the largest rectangle, with sides along the grid lines, that covers nothing but 1s, and return its area as a count of cells. A grid with no 1s at all has answer 0.

Examples

Input:  grid = [[1, 0, 1, 1, 0],
                [1, 1, 1, 1, 0],
                [0, 1, 1, 1, 1],
                [1, 1, 1, 0, 1]]
Output: 6
Why:    rows 1-2 across columns 1-3 are all 1s, and nothing bigger is
Input:  grid = [[1, 1, 0, 1, 1, 1]]
Output: 3
Why:    a single row: the longest run of 1s wins
Input:  grid = [[0, 0], [0, 0]]
Output: 0
Why:    edge case, there is no 1 to start a rectangle from

Hints

0 / 3

Stuck on the idea rather than the code? Largest Rectangle covers it.