Approach
Depth-first search
For Maximum Points After Collecting Coins From All Nodes, 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
- 44 lines of Java from the credited upstream file 2920.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 int maximumPoints(int[][] edges, int[] coins, int k) {3 final int n = coins.length;4 List<Integer>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 Integer[][] mem = new Integer[n][MAX_HALVED + 1];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, -1, coins, k, 0, mem);17 }18 19 private static final int MAX_COIN = 10000;20 private static final int MAX_HALVED = (int) (Math.log(MAX_COIN) / Math.log(2)) + 1;21 22 private int dfs(List<Integer>[] graph, int u, int prev, int[] coins, int k, int halved,23 Integer[][] mem) {24 25 if (halved > MAX_HALVED)26 return 0;27 if (mem[u][halved] != null)28 return mem[u][halved];29 30 final int val = coins[u] / (1 << halved);31 int takeAll = val - k;32 int takeHalf = (int) Math.floor(val / 2.0);33 34 for (final int v : graph[u]) {35 if (v == prev)36 continue;37 takeAll += dfs(graph, v, u, coins, k, halved, mem);38 takeHalf += dfs(graph, v, u, coins, k, halved + 1, mem);39 }40 41 return mem[u][halved] = Math.max(takeAll, takeHalf);42 }43}44