原题链接在这里:https://leetcode.com/problems/maximal-rectangle/
与Largest Rectangle in Histogram相似. 用一个数组dp存储一行中每一个点的最大高度,然后像Largest Rectangle in Histogram算这一行能产生的最大面积maxRec.
Time O(m*n), m是matrix的高,n是matrix的长。Space O(n).
AC Java:
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int h = matrix.length;
int w = matrix[0].length;
// length,length,length,length,length
int [] dp = new int[w];
int maxRec = 0;
for(int i = 0; i<h; i++){
for(int j=0; j<w; j++){
dp[j] = matrix[i][j] == '0' ? 0 : dp[j]+1;
}
maxRec = Math.max(maxRec,helper(dp));
}
return maxRec;
}
private int helper(int [] nums){
if(nums == null || nums.length == 0){
return 0;
}
Stack<Integer> stk = new Stack<Integer>();
int [] h = new int[nums.length + 1];
h = Arrays.copyOf(nums, nums.length+1);
int maxArea = 0;
int i = 0;
while(i<h.length){
if(stk.isEmpty() || h[stk.peek()] <= h[i]){
stk.push(i);
i++;
}else{
int index = stk.pop();
maxArea = Math.max(maxArea,h[index]*(stk.isEmpty() ? i : i-stk.peek()-1));
}
}
return maxArea;
}
}