题目来源:https://leetcode-cn.com/problems/maximal-rectangle/
大致题意:
给定一个仅包含 0 和 1 二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
思路
- 遍历求出每个位置左侧连续的 1 的个数
- 每一列,都可以视为柱状图中最大矩形的一次求解过程,不过左侧连续的 1 的个数表示高
代码:
class Solution {
public int maximalRectangle(char[][] matrix) {
int ans = 0;
int m = matrix.length;
int n = matrix[0].length;
// 每个位置左侧连续的 1 的个数
int[][] left = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
}
}
}
// 每一列,做一次柱状图中最大矩形的求解
for (int col = 0; col < n; col++) {
// 上方比当前位置低的最近的位置
int[] up = new int[m];
// 上方比当前位置低的最近的位置
int[] down = new int[m];
Arrays.fill(down, m);
// 单调栈
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < m; i++) {
while (!stack.isEmpty() && left[stack.peek()][col] >= left[i][col]) {
down[stack.pop()] = i;
}
up[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(i);
}
for (int i = 0; i < m; i++) {
ans = Math.max((down[i] - up[i] - 1) * left[i][col], ans);
}
}
return ans;
}
}