Approach
Depth-first search
For Subtree Inversion Sum, 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
- 38 lines of Java from the credited upstream file 3544.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 subtreeInversionSum(int[][] edges, int[] nums, int k) {3 final int n = edges.length + 1;4 int[] parent = new int[n];5 List<Integer>[] graph = new List[n];6 Arrays.fill(parent, -1);7 Arrays.setAll(graph, i -> new ArrayList<>());8 9 for (int[] edge : edges) {10 final int u = edge[0];11 final int v = edge[1];12 graph[u].add(v);13 graph[v].add(u);14 }15 16 return dfs(graph, 0, k,17 false, nums, k, parent, new Long[n][k + 1][2]);18 }19 20 private long dfs(List<Integer>[] graph, int u, int stepsSinceInversion, boolean inverted,21 int[] nums, int k, int[] parent, Long[][][] mem) {22 if (mem[u][stepsSinceInversion][inverted ? 1 : 0] != null)23 return mem[u][stepsSinceInversion][inverted ? 1 : 0];24 long num = inverted ? -nums[u] : nums[u];25 long negNum = -num;26 for (final int v : graph[u]) {27 if (v == parent[u])28 continue;29 parent[v] = u;30 num += dfs(graph, v, Math.min(k, stepsSinceInversion + 1), inverted, nums, k, parent, mem);31 if (stepsSinceInversion == k)32 negNum += dfs(graph, v, 1, !inverted, nums, k, parent, mem);33 }34 return mem[u][stepsSinceInversion][inverted ? 1 : 0] =35 (stepsSinceInversion == k) ? Math.max(num, negNum) : num;36 }37}38