85 Maximal Rectangle
1. Question
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 02. Implementation
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
Stack<Integer> stack = null;
int area = 0, maxArea = 0;
int m = matrix.length, n = matrix[0].length;
int[] heights = new int[n + 1];
for (int i = 0; i < m; i++) {
stack = new Stack<>();
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
heights[j] += 1;
}
else {
heights[j] = 0;
}
}
for (int j = 0; j <= n; j++) {
int curHeight = j == n ? -1 : heights[j];
while (!stack.isEmpty() && heights[stack.peek()] > curHeight) {
int topIndex = stack.pop();
area = heights[topIndex] * (stack.isEmpty() ? j : j - stack.peek() - 1);
maxArea = Math.max(maxArea, area);
}
stack.push(j);
}
}
return maxArea;
}
}3. Time & Space Complexity
Last updated