-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.py
32 lines (30 loc) · 889 Bytes
/
solution.py
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
"""
206 / 206 test cases passed.
Runtime: 492 ms
Memory Usage: 119 MB
"""
class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
tree = collections.defaultdict(list)
for child, parent in enumerate(parents):
if parent != -1:
tree[parent].append(child)
n = len(parents)
ans = max_score = 0
def dfs(i):
score, cnt = 1, 0
for child in tree[i]:
sz = dfs(child)
cnt += sz
score *= sz
if i != 0:
score *= n - cnt - 1
nonlocal max_score, ans
if score == max_score:
ans += 1
elif score > max_score:
ans = 1
max_score = score
return cnt + 1
dfs(0)
return ans