做这题之前建议先去做力扣 84. 柱状图中最大的矩形,这题实际上是遍历每一行,以每一行为底形成一个柱状图, 柱状图中最大的矩形,然后取得最大值。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix int整型二维数组
* @return int整型
*/
public int maximalRectangle(int[][] matrix) {
int n = matrix.length, m = matrix[0].length;
int[] height = new int[m];
int maxArea=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 1) height[j]++;
else height[j] = 0;
}
maxArea=Math.max(maxArea,getMaxArea(height));
}
return maxArea;
}
public int getMaxArea(int[] height) {
Deque<Integer> stack = new LinkedList<>();
int[] newHeight = new int[height.length + 2];
newHeight[0] = 0;
newHeight[newHeight.length - 1] = 0;
System.arraycopy(height, 0, newHeight, 1, height.length);
stack.push(0);
int maxArea=0;
for (int i = 1; i < newHeight.length; i++) {
if(newHeight[i]>=newHeight[stack.peek()]){
stack.push(i);
}else{
while (!stack.isEmpty()&&newHeight[i]<newHeight[stack.peek()]){
int mid=stack.pop();
if(!stack.isEmpty()){
int left=stack.peek();
int area=(i-left-1)*newHeight[mid];
maxArea=Math.max(maxArea,area);
}
}
stack.push(i);
}
}
return maxArea;
}
}

京公网安备 11010502036488号