Poison

85. Maximal Rectangle

Violence
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
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length, n = matrix[0].length;

int[][] tallMatrix = new int[m][n];
for (int j = 0; j < n; j++) {
tallMatrix[0][j] = matrix[0][j] == '1' ? 1 : 0;
}

for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
if (matrix[i - 1][j] == '1') {
tallMatrix[i][j] = tallMatrix[i - 1][j] + 1;
} else {
tallMatrix[i][j] = 1;
}
}
}
}

int maxArea = 0;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (tallMatrix[i][j] == 0) {
continue;
}
if (tallMatrix[i][j] * n <= maxArea) {
continue;
}

// 寻找左右侧高度大于等于当前柱子的所有柱子
int width = 1; // self
for (int k = j - 1; k >= 0; k--) {
if (tallMatrix[i][k] >= tallMatrix[i][j]) {
width++;
} else {
break;
}
}
for (int k = j + 1; k < n; k++) {
if (tallMatrix[i][k] >= tallMatrix[i][j]) {
width++;
} else {
break;
}
}

maxArea = Math.max(maxArea, width * tallMatrix[i][j]);
}
}

return maxArea;
}
}
Stack
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
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length, n = matrix[0].length;

int maxArea = 0;
int[] heights = new int[n + 2];
for (int rowIndex = 0; rowIndex < m; rowIndex++) {
for (int colIndex = 0; colIndex < n; colIndex++) {
heights[colIndex + 1] = matrix[rowIndex][colIndex] == '1' ? 1 + heights[colIndex + 1] : 0;
}
maxArea = Math.max(maxArea, maximalRectangle(heights));
}

return maxArea;
}

private int maximalRectangle(int[] heights) {
int maxArea = 0;

Stack<Integer> increaseStack = new Stack<>();
for (int i = 0; i < heights.length; i++) {
while (!increaseStack.isEmpty() && heights[i] < heights[increaseStack.peek()]) {
int height = heights[increaseStack.pop()];
int leftIndex = increaseStack.peek(); // exclusive
int rightIndex = i; // exclusive
int width = rightIndex - leftIndex - 1;
maxArea = Math.max(maxArea, height * width);
}

increaseStack.push(i);
}

return maxArea;
}
}
Reference

85. Maximal Rectangle