21. Max Rectangle
β GFG solution to the Max Rectangle problem: find maximum area rectangle in binary matrix using largest rectangle in histogram approach with stack optimization. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a 2D binary matrix mat[][]
, where each cell contains either 0 or 1. Your task is to find the maximum area of a rectangle that can be formed using only 1's within the matrix.
A rectangle is formed by selecting a submatrix where all elements are 1. The goal is to find the rectangle with the maximum possible area.
π Examples
Example 1
Input: mat[][] = [[0, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0]]
Output: 8
Explanation: The largest rectangle with only 1's is from (1, 0) to (2, 3) which is
[1, 1, 1, 1]
[1, 1, 1, 1]
and area is 4 * 2 = 8.
Example 2
Input: mat[][] = [[0, 1, 1],
[1, 1, 1],
[0, 1, 1]]
Output: 6
Explanation: The largest rectangle with only 1's is from (0, 1) to (2, 2) which is
[1, 1]
[1, 1]
[1, 1]
and area is 2 * 3 = 6.
π Constraints
$1 \le \text{mat.size()}, \text{mat[0].size()} \le 1000$
$0 \le \text{mat}[i][j] \le 1$
β
My Approach
The optimal approach transforms this problem into the Largest Rectangle in Histogram problem by treating each row as the base of a histogram:
Histogram + Stack Approach
Transform to Histogram:
For each row, calculate the height of consecutive 1's ending at that row.
If
mat[i][j] = 1
, thenheight[j] = height[j] + 1
If
mat[i][j] = 0
, thenheight[j] = 0
Apply Largest Rectangle in Histogram:
For each row's histogram, find the maximum rectangle area using stack.
Use a monotonic stack to efficiently find the largest rectangle.
Stack Algorithm:
Push indices to stack while heights are increasing.
When a smaller height is found, pop from stack and calculate area.
Width = current_index - previous_stack_top - 1 (or current_index if stack is empty).
Update Maximum:
Track the maximum area found across all rows.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ m), where n is the number of rows and m is the number of columns. For each row, we process the histogram in O(m) time using stack operations where each element is pushed and popped at most once.
Expected Auxiliary Space Complexity: O(m), where m is the number of columns. We use O(m) space for the height array and O(m) space for the stack in the worst case.
π§βπ» Code (C++)
class Solution {
public:
int maxArea(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size(), res = 0;
vector<int> h(m, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
h[j] = mat[i][j] ? h[j] + 1 : 0;
stack<int> st;
for (int j = 0; j <= m; j++) {
int cur = j == m ? 0 : h[j];
while (!st.empty() && h[st.top()] > cur) {
int tp = st.top(); st.pop();
int w = st.empty() ? j : j - st.top() - 1;
res = max(res, h[tp] * w);
}
st.push(j);
}
}
return res;
}
};
β Code (Java)
class Solution {
static int maxArea(int mat[][]) {
int n = mat.length, m = mat[0].length, res = 0;
int[] h = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
h[j] = mat[i][j] == 1 ? h[j] + 1 : 0;
Stack<Integer> st = new Stack<>();
for (int j = 0; j <= m; j++) {
int cur = j == m ? 0 : h[j];
while (!st.isEmpty() && h[st.peek()] > cur) {
int tp = st.pop();
int w = st.isEmpty() ? j : j - st.peek() - 1;
res = Math.max(res, h[tp] * w);
}
st.push(j);
}
}
return res;
}
}
π Code (Python)
class Solution:
def maxArea(self, mat):
n, m, res = len(mat), len(mat[0]), 0
h = [0] * m
for i in range(n):
for j in range(m):
h[j] = h[j] + 1 if mat[i][j] else 0
st = []
for j in range(m + 1):
cur = 0 if j == m else h[j]
while st and h[st[-1]] > cur:
tp = st.pop()
w = j if not st else j - st[-1] - 1
res = max(res, h[tp] * w)
st.append(j)
return res
Note: This Python approach sometimes results in Time Limit Exceeded (TLE) for large inputs (fails ~1110 /1115 test cases due to time constraints).
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated