Problem Description
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. The solution must account for all matrix cells and efficiently compute the maximal area.
Key Insights
- Transform each row into a histogram, where the height at each column is the count of consecutive '1's encountered so far.
- Use a monotonic stack algorithm to compute the largest rectangle area within this histogram.
- Iterate row by row, updating histogram heights and computing the maximal area based on the updated histogram.
- This reduces a 2D problem into repeatedly solving the Largest Rectangle in Histogram problem.
Space and Time Complexity
Time Complexity: O(m*n), where m is the number of rows and n is the number of columns, since each histogram is processed in O(n) for each row. Space Complexity: O(n), needed for the histogram and the stack used in the algorithm.
Solution
The algorithm works by processing each row of the matrix and updating a histogram that represents the number of consecutive '1's for each column up to that row. For every row, we compute the largest rectangle area in the histogram by using a monotonic stack:
- Iterate through each column index in the histogram.
- Use a stack to store column indices such that the heights are in non-decreasing order.
- When a height less than the current height is encountered, pop indices from the stack and calculate the area using the height at the popped index and the current index as the right boundary.
- After processing, ensure remaining indices in the stack are handled.
- The maximum area found over all rows is returned as the answer.