求最大子矩阵的大小(Maximal Rectangle)(原创解法)

题目

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.

中文版


image.png

解答

/**
 * @author vega
 */
public class Main {
    public static void main(String[] args) {
//        int[][] map = new int[][]{{1, 1, 1, 0}};
        int[][] map = new int[][]{
                {1, 0, 1, 1},
                {1, 1, 1, 1},
                {1, 1, 1, 0},
                {1, 0, 1, 0},
                {1, 1, 1, 0}
        };
        int result = solution(map);
        System.out.println(result);
    }

    private static int solution(int[][] map) {
       if (map == null) 
            return 0;
        int max = 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 ? height[j] + 1 : 0;
            }
            max = Math.max(max, getMaxRexSizeFromBottom(height));
        }
        return max;
    }
    private int getMaxRexSizeFromBottom(int[] height) {
        int max = 0;
        Stack<Integer> s = new Stack<Integer>();
        for (int i = 0; i < height.length; i++) {
            while (!s.isEmpty() && height[s.peek()] >= height[i]) {
                int current = s.pop();
                int top = s.isEmpty() ? -1 : s.peek();
                max = Math.max(max, (i - top - 1) * height[current]);
            }
            s.push(i);
        }
        while (!s.isEmpty()) {
            int current = s.pop();
            int top = s.isEmpty() ? -1 : s.peek();
            max = Math.max(max, (height.length - top - 1) * height[current]);
        }
        return max;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 给定一个整数map,其中的值只有0和1两种,求其中全是1的所有矩形区域中最大的矩形区域为1的数量。  例如:...
    呤雪情枫阅读 3,584评论 0 1
  • 这个题考察的是动态规划,并且要了解LeetCode第84题,要清楚直方图的面积怎么计算。 85.最大矩阵(Leet...
    Michaelhbjian阅读 2,839评论 0 0
  • 题目 给定一个整型矩阵map, 其中的值只有0 和 1 两种, 求其中全是1 的所有矩形区域中, 最大的矩形区域为...
    囧略囧阅读 9,544评论 1 2
  • 问题:求一个矩阵中最大子矩阵的大小(长方形)如:1 0 1 11 1 1 11 1 1 0最大子矩阵面积为6
    奈奈要打小怪兽阅读 2,707评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 12,186评论 16 22