Approach
Depth-first search
For Choose Edges to Maximize Score in a Tree, 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
- 39 lines of Java from the credited upstream file 2378.java.
- The implementation visibly relies on sequence storage.
- 2 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 long maxScore(int[][] edges) {3 final int n = edges.length;4 List<Pair<Integer, Integer>>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int i = 0; i < n; ++i) {8 final int parent = edges[i][0];9 final int weight = edges[i][1];10 if (parent != -1)11 graph[parent].add(new Pair<>(i, weight));12 }13 14 Pair<Long, Long> pair = dfs(graph, 0);15 final long takeRoot = pair.getKey();16 final long notTakeRoot = pair.getValue();17 return Math.max(takeRoot, notTakeRoot);18 }19 20 21 22 private Pair<Long, Long> dfs(List<Pair<Integer, Integer>>[] graph, int u) {23 long bestEdge = 0;24 long notTakeU = 0;25 26 for (Pair<Integer, Integer> pair : graph[u]) {27 final int v = pair.getKey();28 final int w = pair.getValue();29 Pair<Long, Long> res = dfs(graph, v);30 final long takeV = res.getKey();31 final long notTakeV = res.getValue();32 bestEdge = Math.max(bestEdge, w + notTakeV - takeV);33 notTakeU += takeV;34 }35 36 return new Pair<>(bestEdge + notTakeU, notTakeU);37 }38}39