-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.js
48 lines (41 loc) · 1.09 KB
/
solution.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
var maximumInvitations = function (favorite) {
const n = favorite.length;
const inDegree = new Array(n).fill(0);
const chainLengths = new Array(n).fill(0);
const visited = new Array(n).fill(false);
favorite.forEach((fav) => inDegree[fav]++);
const queue = [];
for (let i = 0; i < n; i++) {
if (inDegree[i] === 0) {
queue.push(i);
}
}
while (queue.length) {
const node = queue.shift();
visited[node] = true;
const next = favorite[node];
chainLengths[next] = chainLengths[node] + 1;
if (--inDegree[next] === 0) {
queue.push(next);
}
}
let maxCycle = 0,
totalChains = 0;
for (let i = 0; i < n; i++) {
if (!visited[i]) {
let current = i,
cycleLength = 0;
while (!visited[current]) {
visited[current] = true;
current = favorite[current];
cycleLength++;
}
if (cycleLength === 2) {
totalChains += 2 + chainLengths[i] + chainLengths[favorite[i]];
} else {
maxCycle = Math.max(maxCycle, cycleLength);
}
}
}
return Math.max(maxCycle, totalChains);
};