数据结构-全部由1组成的最大子矩形

给定一个二维数组matrix,其中的值不是0就是1,返回全部由1组成的最大子矩形,内部有多少个1.

数组压缩

import java.util.Stack;

public class MaximalRectangle {
    public static void main(String[] args) {
        char[][] map = {
                {'1','1','1','1','1','1'},
                {'1','1','1','0','1','1'},
                {'1','1','1','1','1','1'},
                {'1','0','1','1','1','1'},
                {'1','1','1','1','1','1'},
                {'1','1','1','1','0','1'},
                {'1','1','1','1','1','1'},
        };

        System.out.println(maximalRect(map));
    }

    public static int maximalRect(char[][] map){
        if(map == null || map.length == 0 || map[0].length == 0){
            return 0;
        }

        int maxArea = 0;
        int[] height = new int[map[0].length];
        for (int i = 0; i < map.length; i++) { // 行数
            for (int j = 0; j < map[0].length; j++) { // 列数

                // 数组压缩
                height[j] = map[i][j] == '0' ? 0 : height[j]+1;
            }

            maxArea = Math.max(maxRectFromBottom(height),maxArea);
        }
        return maxArea;
    }

    // height是正方图数组, 使用单调栈求出直方图最大长方形面积
    public static int maxRectFromBottom(int[] height){
        if(height == null || height.length == 0){
            return 0;
        }

        // 3,4,5,6
        int maxArea = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < height.length; i++) {
            while(!stack.isEmpty() && height[stack.peek()] >= height[i]){
                int popIndex = stack.pop();
                int leftIndex = stack.isEmpty() ? -1 : stack.peek();
                int curArea = (i - 1 - leftIndex) * height[popIndex];
                maxArea = Math.max(maxArea, curArea);
            }
            stack.push(i);
        }

        while(!stack.isEmpty()){
            int popIndex = stack.pop();
            int leftIndex = stack.isEmpty() ? -1 : stack.peek();
            int curArea = (height.length - 1 - leftIndex) * height[popIndex];
            maxArea = Math.max(maxArea, curArea);
        }

        return maxArea;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值