-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPriyankaandToys.js
47 lines (38 loc) · 924 Bytes
/
PriyankaandToys.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
// Solution 1
function toys(w) {
const _w = w.slice();
const containers = [];
_w.sort((a, b) => a - b);
for (const num of _w) {
if (!containers[containers.length - 1]) {
containers.push([num]);
continue;
}
if (
num >= containers[containers.length - 1][0] &&
num <= containers[containers.length - 1][0] + 4
) {
containers[containers.length - 1].push(num);
} else {
containers.push([num]);
}
}
return containers.length;
}
// Solution 2
function toys(w) {
const _w = w.slice();
_w.sort((a, b) => a - b);
const containers = [[_w[0]]];
for (let i = 1; i < _w.length; i++) {
if (
_w[i] >= containers[containers.length - 1][0] &&
_w[i] <= containers[containers.length - 1][0] + 4
) {
containers[containers.length - 1].push(_w[i]);
} else {
containers.push([_w[i]]);
}
}
return containers.length;
}