Skip to content

Commit a25d1a8

Browse files
authored
Create 2049-count-nodes-with-the-highest-score.js
1 parent 3e92383 commit a25d1a8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} parents
3+
* @return {number}
4+
*/
5+
const countHighestScoreNodes = function(parents) {
6+
const n = parents.length, graph = {}, hash = {}
7+
for(let i = 1; i < n; i++) {
8+
if(graph[parents[i]] == null) graph[parents[i]] = []
9+
graph[parents[i]].push(i)
10+
}
11+
dfs(0)
12+
13+
function dfs(node) {
14+
let product = 1, num = 0
15+
for(let child of (graph[node] || [])) {
16+
const tmp = dfs(child)
17+
product *= tmp
18+
num += tmp
19+
}
20+
if(n - 1 - num > 0) product *= (n - 1 - num)
21+
hash[product] = (hash[product] || 0) + 1
22+
return num + 1
23+
}
24+
const maxKey = Math.max(...Object.keys(hash))
25+
return hash[maxKey]
26+
};

0 commit comments

Comments
 (0)