Maximal Rectangle LeetCode solution in JavaScript

1
var maximalRectangle = function (matrix) {
2
const m = matrix.length;
3
const n = matrix[m - 1].length;
4

5
const prefixSum = new Array(m).fill().map(() => new Array(n).fill(0));
6
for (let i = 0; i < m; i += 1) {
7
for (let j = 0; j < n; j += 1) {
8
prefixSum[i][j] = parseInt(matrix[i][j]);
9
if (i > 0 && prefixSum[i][j] > 0) {
10
prefixSum[i][j] += prefixSum[i - 1][j];
11
}
12
}
13
}
14

15
const getArea = (currentRow) => {
16
let max = 0;
17
for (let i = 0; i < n; i += 1) {
18
const height = currentRow[i];
19

20
let leftBoundary = i;
21
while (leftBoundary >= 0 && currentRow[leftBoundary] >= currentRow[i]) {
22
leftBoundary -= 1;
23
}
24

25
let rightBoundary = i;
26
while (rightBoundary < n && currentRow[rightBoundary] >= currentRow[i]) {
27
rightBoundary += 1;
28
}
29

30
const width = rightBoundary - leftBoundary - 1;
31
max = Math.max(max, height * width);
32
}
33

34
return max;
35
};
36

37
let max = 0;
38
for (let i = 0; i < m; i += 1) {
39
max = Math.max(max, getArea(prefixSum[i]));
40
}
41

42
return max;
43
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0