-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximal Rectangle.java
30 lines (25 loc) · 1.04 KB
/
Maximal Rectangle.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
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int rows = matrix.length;
int cols = matrix[0].length;
int[] heights = new int[cols + 1]; // Include an extra element for easier calculation
int maxArea = 0;
for (char[] row : matrix) {
for (int i = 0; i < cols; i++) {
heights[i] = (row[i] == '1') ? heights[i] + 1 : 0;
}
// Calculate max area using histogram method
int n = heights.length; // Number of bars in the histogram
for (int i = 0; i < n; i++) {
for (int j = i, minHeight = Integer.MAX_VALUE; j < n; j++) {
minHeight = Math.min(minHeight, heights[j]);
int area = minHeight * (j - i + 1);
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
}