Maximal Rectangle

update Sep 25 2018, 21:53

LeetCodearrow-up-right

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

Basic Idea:

对于这道题目,我们不可以用 Maximal Square 那道题的dp方法,因为每个顶点对应的可能的长方形有很多种可能。

这道题的方法是先利用dp求每个点上方连续 '1' 的个数,然后每一层就相当于一个histogram,接下来对于每层用 maximal rectangle in histogram 的方法求出最大矩形面积,返回全局最大值即可。

时间复杂度: 求每个点上方连续1的个数耗时 O(mn),求每行最大面积耗时 O(n),总耗时O(mn);

Java Code: