https://leetcode-cn.com/problems/maximal-rectangle/submissions/
思路:
这道题的做法与leetcode084很相像
对每一行求一次柱状图中最大的矩形,通过辅助数组heights记录每一列的柱状图高度即可
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
int ans = 0 ;
for(int i = 0;i<heights.length;i++){
while(stack.peek()!=-1&&heights[stack.peek()]>=heights[i]){
ans = Math.max(ans,heights[stack.pop()]*(i-stack.peek()-1));
}
stack.push(i);
}
while (stack.peek() != -1) {
ans = Math.max(ans,heights[stack.pop()]*(heights.length-stack.peek()-1));
}
return ans;
}
public int maximalRectangle(char[][] matrix) {
if(matrix.length==0){
return 0;
}
int ans = 0;
int[] heights = new int[matrix[0].length];
for(int r = 0;r<matrix.length;r++){
for(int c = 0;c<matrix[0].length;c++){
if(matrix[r][c]=='1'){
heights[c] +=1;
}
else{
heights[c] = 0;
}
}
ans = Math.max(largestRectangleArea(heights),ans);
}
return ans;
}
}