JAVA solution based on Maximal Rectangle 370ms


  • 0
    S
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int[] height = new int[matrix[0].length];
        int res = 0;
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++)
                height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0;
            res = Math.max(res, largestRectangleArea(height));
        }
        return res;
    }
    
    public int largestRectangleArea(int[] height) {
        if(height == null || height.length == 0)
            return 0;
        Stack<Integer> stk = new Stack<Integer>();
        int max = 0;
        
        for(int i = 0; i < height.length; i++){
            while(!stk.isEmpty() && height[stk.peek()] > height[i]){
                int index = stk.pop();
                int curArea = stk.isEmpty()? (int) Math.pow(Math.min(i, height[index]), 2) :
                                             (int) Math.pow(Math.min(i - stk.peek() - 1, height[index]), 2);
                max = Math.max(max, curArea);
            }
            stk.push(i);
        }
        
        while(!stk.isEmpty()){
            int index = stk.pop();
            int curArea = stk.isEmpty()? (int) Math.pow(Math.min(height.length, height[index]), 2) : 
                                         (int) Math.pow(Math.min(height.length - stk.peek() - 1, height[index]), 2);
            max = Math.max(max, curArea);
        }
        return max;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.