-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathmaximal-rectangle.js
70 lines (59 loc) · 1.37 KB
/
maximal-rectangle.js
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
/**
* Maximal Rectangle
*
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
*
* Example:
*
* Input:
* [
* ["1","0","1","0","0"],
* ["1","0","1","1","1"],
* ["1","1","1","1","1"],
* ["1","0","0","1","0"]
* ]
* Output: 6
*/
/**
* @param {character[][]} matrix
* @return {number}
*/
const maximalRectangle = matrix => {
if (!matrix || matrix.length === 0) {
return 0;
}
const m = matrix.length;
const n = matrix[0].length;
const left = Array(n).fill(0);
const right = Array(n).fill(n - 1);
const height = Array(n).fill(0);
let maxArea = 0;
for (let i = 0; i < m; i++) {
let currLeft = 0;
let currRight = n;
for (let j = 0; j < n; j++) {
height[j] = matrix[i][j] === '1' ? height[j] + 1 : 0;
}
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1') {
left[j] = Math.max(currLeft, left[j]);
} else {
left[j] = 0;
currLeft = j + 1;
}
}
for (let j = n - 1; j >= 0; j--) {
if (matrix[i][j] === '1') {
right[j] = Math.min(currRight, right[j]);
} else {
right[j] = n - 1;
currRight = j - 1;
}
}
for (let j = 0; j < n; j++) {
maxArea = Math.max(maxArea, (right[j] - left[j] + 1) * height[j]);
}
}
return maxArea;
};
export { maximalRectangle };