码迷,mamicode.com
首页 > 其他好文 > 详细

85. Maximal Rectangle

时间:2018-11-06 13:25:38      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:max   for   pre   avr   ||   ges   ima   har   int   

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing only 1‘s and return its area.
Example:
Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6



https://www.youtube.com/watch?v=2Yk3Avrzauk&t=450s



class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
        int row = matrix.length;
        int col = matrix[0].length;
        int[] height = new int[col];
        int max = 0;
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(matrix[i][j] == ‘1‘){
                    height[j]++;
                }else{
                    height[j] = 0;
                }
            }
            int area = largestArea(height);
            max = Math.max(area, max);
        }
        return max;
    }
    private int largestArea(int[] height){
        int len = height.length;
        Stack<Integer> s = new Stack<Integer>();
        int maxArea = 0;
        for(int i = 0; i <= len; i++){
            int h = (i == len ? 0 : height[i]);
            if(s.isEmpty() || h >= height[s.peek()]){
                s.push(i);
            }else{
                int tp = s.pop();
                maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
                i--;
            }
        }
        return maxArea;
    }
}

 

85. Maximal Rectangle

标签:max   for   pre   avr   ||   ges   ima   har   int   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9914452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!