Problem description:

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Input:
[[“1”,”0”,”1”,”0”,”0”],
[“1”,”0”,”1”,”1”,”1”],
[“1”,”1”,”1”,”1”,”1”],
[“1”,”0”,”0”,”1”,”0”]]
Output: 6

Analysis:

This is a typical dynamic programming problem. We keep three matrices: left, right, height, all have the same size as the input. Here’s a great explanation of what these matrices represent from Leetcode user @wahcheung in Chinese. The key to understand this algorithm is clarify what left and right matrix each represents.

In the example above, the left, right, height are as follows:

The maximum rectangle at (i, j) would be calculated as (right(i, j) - left(i, j)) * height(i, j).

In the implementation, in order to reduce space complexity, instead of using actual matrices, we keep three arrays to proceed and update row by row.

Java Code:

MaximumRectangle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MaximumRectangle {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0) return 0;
int res = 0;
int n = matrix[0].length;
int[] left = new int[n];
int[] right = new int[n];
int[] height = new int[n];

Arrays.fill(right, n);

for (int i = 0; i < matrix.length; i++) {
int curLeft = 0;
int curRight = n;
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') {
height[j] = 0;
left[j] = 0;
curLeft = j + 1;
} else {
height[j]++;
left[j] = Math.max(left[j], curLeft);
}
}

for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '0') {
curRight = j;
right[j] = n;
} else {
right[j] = Math.min(right[j], curRight);
}
}

for (int j = 0; j < n; j++) {
res = Math.max(res, (right[j] - left[j]) * height[j]);
}
}
return res;
}
}