Maximum White Tiles Covered by a Carpet LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} tiles
3
* @param {number} carpetLen
4
* @return {number}
5
*/
6
var maximumWhiteTiles = function (tiles, carpetLen) {
7
const sorted = tiles.sort((a, b) => a[0] - b[0]);
8
let res = 0;
9

10
let total = 0;
11
let right = 0;
12

13
for (let tile of sorted) {
14
const start = tile[0];
15
const end = start + carpetLen - 1;
16
while (right < sorted.length && tiles[right][1] < end) {
17
total += tiles[right][1] - tiles[right][0] + 1;
18
right += 1;
19
}
20
if (right === sorted.length || sorted[right][0] > end) {
21
res = Math.max(res, total);
22
} else {
23
res = Math.max(res, total + (end - tiles[right][0] + 1));
24
}
25
total -= tile[1] - tile[0] + 1;
26
}
27

28
return res;
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0