Approach
Depth-first search
For Count Nodes With the Highest Score, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 40 lines of Java from the credited upstream file 2049.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int countHighestScoreNodes(int[] parents) {3 List<Integer>[] tree = new List[parents.length];4 5 for (int i = 0; i < tree.length; ++i)6 tree[i] = new ArrayList<>();7 8 for (int i = 0; i < parents.length; ++i) {9 if (parents[i] == -1)10 continue;11 tree[parents[i]].add(i);12 }13 14 dfs(tree, 0);15 return ans;16 }17 18 private int ans = 0;19 private long maxScore = 0;20 21 private int dfs(List<Integer>[] tree, int u) {22 int count = 1;23 long score = 1;24 for (final int v : tree[u]) {25 final int childCount = dfs(tree, v);26 count += childCount;27 score *= childCount;28 }29 final int aboveCount = tree.length - count;30 score *= Math.max(aboveCount, 1);31 if (score > maxScore) {32 maxScore = score;33 ans = 1;34 } else if (score == maxScore) {35 ++ans;36 }37 return count;38 }39}40