-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.java
50 lines (43 loc) · 1.42 KB
/
solution.java
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
class Solution {
public int maximumInvitations(int[] favorite) {
int n = favorite.length;
int[] inDegree = new int[n];
int[] chainLengths = new int[n];
boolean[] visited = new boolean[n];
for (int fav : favorite) {
inDegree[fav]++;
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; ++i) {
if (inDegree[i] == 0) {
queue.offer(i);
}
}
while (!queue.isEmpty()) {
int node = queue.poll();
visited[node] = true;
int next = favorite[node];
chainLengths[next] = chainLengths[node] + 1;
if (--inDegree[next] == 0) {
queue.offer(next);
}
}
int maxCycle = 0, totalChains = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
int 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);
}
}