#2049
Count Nodes With the Highest Score
MediumArrayTreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a single DFS to calculate subtree sizes and scores in one pass, reducing redundant calculations. By leveraging the total number of nodes, we can efficiently compute scores without recalculating subtree sizes multiple times.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS to calculate the size of each subtree and store it.
- 2Step 2: Use the total size of the tree to compute the score for each node based on its children's subtree sizes.
- 3Step 3: Track the maximum score and count how many nodes achieve this score.
solution.py27 lines
1def countHighestScoreNodes(parents):
2 n = len(parents)
3 children = [[] for _ in range(n)]
4 for i in range(1, n):
5 children[parents[i]].append(i)
6 subtree_sizes = [0] * n
7 def dfs(node):
8 size = 1
9 for child in children[node]:
10 size += dfs(child)
11 subtree_sizes[node] = size
12 return size
13 dfs(0)
14 max_score = 0
15 count = 0
16 for i in range(n):
17 score = 1
18 for child in children[i]:
19 score *= subtree_sizes[child]
20 if i != 0:
21 score *= (n - subtree_sizes[i])
22 if score > max_score:
23 max_score = score
24 count = 1
25 elif score == max_score:
26 count += 1
27 return countℹ
Complexity note: This complexity is efficient because we only traverse the tree once to calculate subtree sizes and then again to compute scores, leading to a linear time complexity.
- 1Understanding how to calculate subtree sizes is crucial for optimizing the score calculation.
- 2Using DFS allows us to gather necessary information in a single pass, avoiding redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.