Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
Solution1:转直方图后 利用84题 stack 方式求解
思路:
m次:先每行累计变成直方图,如果元素为0,累积直方图的位置是0.
每一次累积调用一下84题直方图面积求最大。
最终求得全局最大。
Time Complexity: O(mn) Space Complexity: O(nn)
Solution2:DP
思路:
Time Complexity: O(mn) Space Complexity: O(mn)
Solution1 Code:
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int[] heights = new int[matrix[0].length];
int max = 0;
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == '1') {
heights[j]++;
}
else {
heights[j] = 0;
}
}
int area = largestRectangleArea(heights);
max = Math.max(max, area);
}
return max;
}
// directly copy from 84. Largest Rectangle in Histogram
private int largestRectangleArea(int[] heights) {
if(heights == null || heights.length == 0) return 0;
int max = 0;
Deque stack = new ArrayDeque<>();
for(int cur = 0; cur < heights.length; cur++) {
// (1) 遇到增长的就将其index push至stack;
if(stack.isEmpty() || heights[cur] >= heights[stack.peek()]) {
stack.push(cur);
}
// (2) 遇到减的时候得到此柱上一个柱的右边界:此柱。
// 则能计算上一个柱以其自身的max = (其右边界-左边界) * 其高度
else {
int right_border = cur;
int index = stack.pop();
while(!stack.isEmpty() && heights[index] == heights[stack.peek()]) { // 等高情况
index = stack.pop();
}
int left_border = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max, (right_border - left_border - 1) * heights[index]);
cur--; // 重新从此柱
}
}
// 余下单调栈
int right_border = stack.peek() + 1;
while(!stack.isEmpty()) {
int index = stack.pop();
int left_border = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max, (right_border - left_border - 1) * heights[index]);
}
return max;
}
}
Solution2 Code: