forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
39 lines (37 loc) · 876 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
class Solution {
private List<Integer>[] g;
private int ans;
private long mx;
private int n;
public int countHighestScoreNodes(int[] parents) {
n = parents.length;
g = new List[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 1; i < n; ++i) {
g[parents[i]].add(i);
}
dfs(0, -1);
return ans;
}
private int dfs(int i, int fa) {
int cnt = 1;
long score = 1;
for (int j : g[i]) {
if (j != fa) {
int t = dfs(j, i);
cnt += t;
score *= t;
}
}
if (n - cnt > 0) {
score *= n - cnt;
}
if (mx < score) {
mx = score;
ans = 1;
} else if (mx == score) {
++ans;
}
return cnt;
}
}