Engineering platform~35 min2s · 256 MBtarget O(rows × columns) time, O(columns) spaceclassic twin: lc-85monotonic-stack
A cloud scheduler places a big job on machines that sit in a grid of racks and slots. Each cell is a machine. A free machine is marked 1, and a machine that is taken is marked 0.
A job needs a solid rectangle of free machines, so that its parts are close together. The scheduler wants the largest rectangle it can find, measured in machines. The grid can have 200 rows and 200 columns.
Write largest_free_block(grid).
grid is a list of rows. Every row is a string of the same length, made of 1 (free) and 0 (taken).Input: grid = ["0110", "1111", "1110", "0100"]
Output: 6Keep a height for each column: the number of free cells in a row going up from the current row. Then the largest block that ends at the current row is the largest rectangle under the bars of these heights.
| After the row | Heights per column | Largest rectangle under them |
|---|---|---|
0110 |
0, 1, 1, 0 | 2 |
1111 |
1, 2, 2, 1 | 4 |
1110 |
2, 3, 3, 0 | 6 |
0100 |
0, 4, 0, 0 | 4 |
The best is 6: rows 1 and 2 (counting from 0), with columns 0 to 2. It is 2 rows by 3 columns. The columns 1 and 2 also hold a block of 3 rows by 2 columns, which is 6 as well.
Input: grid = ["111", "111"]
Output: 6All six cells are free, so the whole grid is a block.
Input: grid = ["0"]
Output: 0There is no free cell.
1 ≤ rows, columns ≤ 2000 or 1There are about 200^4 / 4 = 400 million rectangles, and checking each cell of each rectangle adds another factor. That is far too slow.
The grid has only 40,000 cells. A method that handles each row in time proportional to its length takes about 40,000 steps for the whole grid.