题目地址:
https://www.lintcode.com/problem/maximal-rectangle/description
给定一个 0 − 1 0-1 0−1矩阵 A A A,求其所含的最大矩形的面积。
可以先参考https://blog.csdn.net/qq_46105170/article/details/108526896再做此题。我们可以对每个位置 ( i , j ) (i,j) (i,j)求一下以它为底的柱子有多高,这样对每一行求一下Largest Rectangle in Histogram即可。设 f [ i ] [ j ] f[i][j] f[i][j]表示位置 ( i , j ) (i,j) (i,j)为底的柱子有多高,那么就有: f [ i ] [ j ] = { 0 , A [ i ] [ j ] = 0 1 + f [ i − 1 ] [ j ] , A [ i ] [ j ] ≠ 0 f[i][j]=\begin{cases}0,A[i][j]=0\\1+f[i-1][j],A[i][j]\ne 0\end{cases} f[i][j]={0,A[i][j]=01+f[i−1][j],A[i][j]=0对每个 f [ i ] f[i] f[i]求一下Largest Rectangle in Histogram即可。代码如下:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
/**
* @param matrix: a boolean 2D matrix
* @return: an integer
*/
public int maximalRectangle(boolean[][] matrix) {
// write your code here
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int res = 0;
int[] dp = new int[matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (!matrix[i][j]) {
dp[j] = 0;
} else {
if (i > 0) {
dp[j] += 1;
} else {
dp[j] = 1;
}
}
}
res = Math.max(res, compute(dp));
}
return res;
}
private int compute(int[] heights) {
int res = 0;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(-1);
for (int i = 0; i < heights.length; i++) {
while (stack.peek() != -1 && heights[stack.peek()] > heights[i]) {
int top = stack.pop();
res = Math.max(res, heights[top] * (i - stack.peek() - 1));
}
stack.push(i);
}
while (stack.peek() != -1) {
int top = stack.pop();
res = Math.max(res, heights[top] * (heights.length - stack.peek() - 1));
}
return res;
}
}
时间复杂度 O ( m n ) O(mn) O(mn),空间 O ( n ) O(n) O(n)。