forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximalRectangle.java
More file actions
Latest commit
42 lines (41 loc) · 1.05 KB
/
Copy pathMaximalRectangle.java
File metadata and controls
42 lines (41 loc) · 1.05 KB
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
/**
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
* containing all ones and return its area.
*/
publicclassMaximalRectangle {
publicintmaximalRectangle(char[][] matrix) {
introws = matrix.length;
if (rows == 0)
return0;
intmaxArea = 0;
intcols = matrix[0].length;
int[][] map = newint[rows][cols];
for (intj = 0; j < cols; j++) {
map[0][j] = matrix[0][j] == '0' ? 0 : 1;
}
for (inti = 1; i < rows; i++) {
for (intj = 0; j < cols; j++) {
map[i][j] = matrix[i][j] == '0' ? map[i - 1][j]
: map[i - 1][j] + 1;
}
}
int[] row = newint[cols];
for (inti = 0; i < rows; i++) {
for (intj = i; j < rows; j++) {
for (intk = 0; k < cols; k++) {
row[k] = map[j][k] - (i == 0 ? 0 : map[i - 1][k]);
}
intcount = 0;
for (intk = 0; k < cols; k++) {
if (row[k] == j - i + 1) {
maxArea = Math.max(maxArea, ++count * (j - i + 1));
} else {
maxArea = Math.max(maxArea, count * (j - i + 1));
count = 0;
}
}
}
}
returnmaxArea;
}
}