85. 最大矩形
Posted zzytxl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了85. 最大矩形相关的知识,希望对你有一定的参考价值。
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] 输出: 6
class Solution { public int maximalRectangle(char[][] matrix) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; int m = matrix.length; int n = matrix[0].length; int res = 0; int[] dp = new int[matrix[0].length]; for(int i = 0;i < m;i++){ for(int j = 0;j < n;j++){ dp[j] = matrix[i][j] == ‘1‘ ? dp[j] + 1 : 0; } res = Math.max(res,getL(dp)); } return res; } private int getL(int[] nums){ //单调增栈 Stack<Integer> stack = new Stack<>(); stack.push(-1); int res = 0; for(int i = 0;i < nums.length;i++){ while(stack.peek() != -1 && nums[stack.peek()] >= nums[i]){ res = Math.max(res,nums[stack.pop()] * (i - stack.peek() - 1)); } stack.push(i); } while(stack.peek() != -1){ res = Math.max(res, nums[stack.pop()] * (nums.length - stack.peek() - 1)); } return res; } }
以上是关于85. 最大矩形的主要内容,如果未能解决你的问题,请参考以下文章