Approach
Depth-first search
For Minimum Score After Removals on 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
- 79 lines of Java from the credited upstream file 2322.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 8 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 minimumScore(int[] nums, int[][] edges) {3 final int n = nums.length;4 final int xors = getXors(nums);5 int[] subXors = nums.clone();6 List<Integer>[] tree = new List[n];7 Set<Integer>[] children = new Set[n];8 9 for (int i = 0; i < n; ++i)10 tree[i] = new ArrayList<>();11 12 for (int i = 0; i < n; ++i)13 children[i] = new HashSet<>(Arrays.asList(i));14 15 for (int[] edge : edges) {16 final int u = edge[0];17 final int v = edge[1];18 tree[u].add(v);19 tree[v].add(u);20 }21 22 dfs(tree, 0, -1, subXors, children);23 24 int ans = Integer.MAX_VALUE;25 26 for (int i = 0; i < edges.length; ++i) {27 int a = edges[i][0];28 int b = edges[i][1];29 if (children[a].contains(b)) {30 final int temp = a;31 a = b;32 b = a;33 }34 for (int j = 0; j < i; ++j) {35 int c = edges[j][0];36 int d = edges[j][1];37 if (children[c].contains(d)) {38 final int temp = c;39 c = d;40 d = temp;41 }42 int[] cands;43 if (a != c && children[a].contains(c))44 cands = new int[] {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]};45 else if (a != c && children[c].contains(a))46 cands = new int[] {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]};47 else48 cands = new int[] {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]};49 ans = Math.min(ans, Arrays.stream(cands).max().getAsInt() -50 Arrays.stream(cands).min().getAsInt());51 }52 }53 54 return ans;55 }56 57 private Pair<Integer, Set<Integer>> dfs(List<Integer>[] tree, int u, int prev, int[] subXors,58 Set<Integer>[] children) {59 for (final int v : tree[u]) {60 if (v == prev)61 continue;62 final Pair<Integer, Set<Integer>> pair = dfs(tree, v, u, subXors, children);63 final int vXor = pair.getKey();64 final Set<Integer> vChildren = pair.getValue();65 subXors[u] ^= vXor;66 for (final int child : vChildren)67 children[u].add(child);68 }69 return new Pair<>(subXors[u], children[u]);70 }71 72 private int getXors(int[] nums) {73 int xors = 0;74 for (final int num : nums)75 xors ^= num;76 return xors;77 }78}79