Given a rows × cols binary matrix filled with '0's and '1's, find the largest rectangle containing only '1's and return its area.
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]6matrix = [["0"]]0matrix = [["1"]]1heights[0..n-1] = 0, maxArea = 0heights[c] += 1 if cell is '1', else reset to 0heights[] using monotonic stacki: area = heights[i] × width; update maxAreamaxArea after all rowsFor each row, heights[c] counts how many consecutive '1's end at that cell going upward. This transforms each row into a histogram problem (LC 84). The largest rectangle in that histogram is the biggest all-'1' rectangle whose bottom edge sits on that row. Running this for every row and taking the maximum gives the global answer in O(m × n).
Checking every possible rectangle is far too slow. But each row can be turned into the previous problem: Largest Rectangle in Histogram.
Build a histogram for each row: the height of a column is the number of consecutive 1s ending at that row. A 0 resets that column to height 0. Run the histogram stack algorithm on each row, and keep the largest area.
A 2D rectangle problem becomes a 1D histogram per row. Reuse the monotonic stack from problem 84.
Run the animation above on your own input, or watch the 1:25 video explanation of Maximal Rectangle with a dry run and Java code.