Given a rows x colsΒ binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Β
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]]
Output: 0
Example 3:
Input: matrix = [["1"]]
Output: 1
Β
Constraints:
rows == matrix.length
cols == matrix[i].length
1 <= rows, cols <= 200
matrix[i][j] is '0' or '1'.
Solutions
Solution 1: Monotonic Stack
We can treat each row as the base of a histogram and calculate the maximum area of the histogram for each row.
Specifically, we maintain an array \(\textit{heights}\) with the same length as the number of columns in the matrix, where \(\textit{heights}[j]\) represents the height of the column at the \(j\)-th position with the current row as the base. For each row, we iterate through each column:
If the current element is '1', increment \(\textit{heights}[j]\) by \(1\).
If the current element is '0', set \(\textit{heights}[j]\) to \(0\).
Then, we use the monotonic stack algorithm to calculate the maximum rectangle area of the current histogram and update the answer.
The specific steps of the monotonic stack are as follows:
Initialize an empty stack \(\textit{stk}\) to store the indices of the columns.
Initialize two arrays \(\textit{left}\) and \(\textit{right}\), representing the index of the first column to the left and right of each column that is shorter than the current column.
Iterate through the heights array \(\textit{heights}\), first calculating the index of the first column to the left of each column that is shorter than the current column, and store it in \(\textit{left}\).
Then iterate through the heights array \(\textit{heights}\) in reverse order, calculating the index of the first column to the right of each column that is shorter than the current column, and store it in \(\textit{right}\).
Finally, calculate the maximum rectangle area for each column and update the answer.
The time complexity is \(O(m \times n)\), where \(m\) is the number of rows in \(matrix\) and \(n\) is the number of columns in \(matrix\).