Repository navigation
Expand file tree
/
Copy pathP85_Maximal_Rectangle.java
More file actions
59 lines (55 loc) · 1.85 KB
/
Copy pathP85_Maximal_Rectangle.java
File metadata and controls
59 lines (55 loc) · 1.85 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package solution.hard;
import java.util.Arrays;
/**
* @author Yi-Lo
* 2020/12/10 17:14
* @version 1.0
* @topics Stack、Array、Hash Table、Dynamic Programming
* @urllink https://leetcode-cn.com/problems/maximal-rectangle/
*/
public class P85_Maximal_Rectangle {
public static int maximalRectangle(char[][] matrix) {
if (matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length;
int[] left = new int[n];
int[] right = new int[n];
int[] height = new int[n];
Arrays.fill(right, n);
int maxArea = 0;
for (int i = 0; i < m; i++) {
int cur_left = 0, cur_right = n;
// update height
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') height[j]++;
else height[j] = 0;
}
// update left
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
left[j] = Math.max(left[j], cur_left);
} else {
left[j] = 0;
cur_left = j + 1;
}
}
// update right
for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '1') {
right[j] = Math.min(right[j], cur_right);
} else {
right[j] = n;
cur_right = j;
}
}
// update area
for (int j = 0; j < n; j++) {
maxArea = Math.max(maxArea, (right[j] - left[j]) * height[j]);
}
}
return maxArea;
}
public static void main(String[] args) {
char[][] matrix = {{'1', '0', '1', '0', '0'}, {'1', '0', '1', '1', '1'}, {'1', '1', '1', '1', '1'}, {'1', '0', '0', '1', '0'}};
System.out.println(maximalRectangle(matrix));
}
}