-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
42 lines (39 loc) · 959 Bytes
/
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
class Solution {
private int n;
private long maxScore;
private int ans;
private List<List<Integer>> graph;
public int countHighestScoreNodes(int[] parents) {
n = parents.length;
maxScore = 0;
ans = 0;
graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 1; i < n; i++) {
graph.get(parents[i]).add(i);
}
dfs(0);
return ans;
}
private int dfs(int cur) {
int size = 1;
long score = 1;
for (int child : graph.get(cur)) {
int s = dfs(child);
size += s;
score *= s;
}
if (cur > 0) {
score *= n - size;
}
if (score > maxScore) {
maxScore = score;
ans = 1;
} else if (score == maxScore) {
ans++;
}
return size;
}
}