85. 最大矩形
难度:困难
给定一个仅包含 0
和 1
、大小为 rows x cols
的二维二进制矩阵,找出只包含 1
的最大矩形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = [["0"]]
输出:0
示例 4:
输入:matrix = [["1"]]
输出:1
示例 5:
输入:matrix = [["0","0"]]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j]
为'0'
或'1'
解答:
class Solution {
//单调栈
//时间复杂度O(MN), 空间复杂度O(MN)
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0) return 0;
int[] heights = new int[matrix[0].length];
int maxAns = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] == '1') heights[j] += 1;
else heights[j] = 0;
}
maxAns = Math.max(maxAns, largestRectangleArea(heights));
}
return maxAns;
}
public int largestRectangleArea(int[] heights){
int[] stack = new int[heights.length + 1];
int topIndex = 0;
int maxAns = 0;
stack[topIndex++] = -1;
for(int i = 1; i < heights.length; i++){
while(topIndex > 0 && heights[stack[topIndex]] > heights[i]){
maxAns = Math.max(maxAns, heights[stack[topIndex]] * (i - stack[topIndex - 1] - 1));
topIndex--;
}
stack[++topIndex] = i;
}
while(topIndex > 0){
maxAns = Math.max(maxAns, heights[stack[topIndex]] * (heights.length - stack[topIndex - 1] - 1));
topIndex--;
}
return maxAns;
}
}
参考自:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/maximal-rectangle/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-1-8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。