-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0085.java
More file actions
80 lines (72 loc) · 2.6 KB
/
Copy pathLeetCode0085.java
File metadata and controls
80 lines (72 loc) · 2.6 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* Maximal Rectangle
* Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
* Output: 6
* */
import java.util.Stack;
public class LeetCode0085 {
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));
}
public static int maximalRectangle(char[][] matrix) {
// 动态规划,计算每行连续1的个数,时间复杂度O(N^2M)
/*if (matrix.length == 0)
return 0;
int row = matrix.length;
int column = matrix[0].length;
int max = 0;
int[][] dp = new int[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = j == 0 ? 1 : dp[i][j - 1] + 1;
int width = dp[i][j];
// 从右下角向上计算矩形面积
for (int k = i; k >= 0; k--) {
width = Math.min(width, dp[k][j]);
max = Math.max(max, width * (i - k + 1));
}
}
}
}
return max;*/
// 利用84题中的单调递增栈
if (matrix.length == 0)
return 0;
int row = matrix.length;
int column = matrix[0].length;
int max = 0;
int[] dp = new int[column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
if (matrix[i][j] == '1')
dp[j] += 1;
else
dp[j] = 0;
}
max = Math.max(leetcode84(dp), max);
}
return max;
}
public static int leetcode84(int[] heights) {
int len = heights.length;
//单调递增栈
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int max = 0;
for (int i = 0; i < len; ++i) {
while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {
int h = heights[stack.pop()];
int w = i - stack.peek() - 1;
max = Math.max(max, w * h);
}
stack.push(i);
}
while (stack.peek() != -1) {
int h = heights[stack.pop()];
int w = len - stack.peek() - 1;
max = Math.max(max, w * h);
}
return max;
}
}