Maximal Rectangle
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix.length == 0) return 0;
// 先算出每个元素上方连续‘1’的个数
int[][] aux = new int[matrix.length][matrix[0].length];
for (int c = 0; c < matrix[0].length; ++c) {
for (int r = 0; r < matrix.length; ++r) {
int prev = r > 0 ? aux[r - 1][c] : 0;
aux[r][c] = matrix[r][c] == '1' ? 1 + prev : 0;
}
}
// 利用求largest rectangle in histogram的方法对每一行求最大面积
int ret = 0;
for (int r = 0; r < aux.length; ++r) {
ret = Math.max(ret, getMaxArea(aux[r]));
}
return ret;
}
private int getMaxArea(int[] input) {
int[] arr = new int[input.length + 1];
for (int i = 0; i < input.length; ++i) arr[i] = input[i];
Deque<Integer> stack = new ArrayDeque<>();
int ret = 0;
for (int i = 0; i < arr.length; ++i) {
if (stack.isEmpty() || arr[stack.peekLast()] <= arr[i]) {
stack.offerLast(i);
} else {
while (! stack.isEmpty() && arr[stack.peekLast()] > arr[i]) {
int peek = stack.pollLast();
int width = stack.isEmpty() ? i : i - stack.peekLast() - 1;
ret = Math.max(arr[peek] * width, ret);
}
stack.offerLast(i);
}
}
return ret;
}
}