Approach
Depth-first search
For Find Number of Coins to Place in Tree 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
- 68 lines of Java from the credited upstream file 2973.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 ChildCost {2 public ChildCost(int cost) {3 if (cost > 0)4 maxPosCosts.add(cost);5 else6 minNegCosts.add(cost);7 }8 9 public void update(ChildCost childCost) {10 numNodes += childCost.numNodes;11 maxPosCosts.addAll(childCost.maxPosCosts);12 minNegCosts.addAll(childCost.minNegCosts);13 maxPosCosts.sort(Comparator.reverseOrder());14 minNegCosts.sort(Comparator.naturalOrder());15 if (maxPosCosts.size() > 3)16 maxPosCosts = maxPosCosts.subList(0, 3);17 if (minNegCosts.size() > 2)18 minNegCosts = minNegCosts.subList(0, 2);19 }20 21 public long maxProduct() {22 if (numNodes < 3)23 return 1;24 if (maxPosCosts.isEmpty())25 return 0;26 long res = 0;27 if (maxPosCosts.size() == 3)28 res = (long) maxPosCosts.get(0) * maxPosCosts.get(1) * maxPosCosts.get(2);29 if (minNegCosts.size() == 2)30 res = Math.max(res, (long) minNegCosts.get(0) * minNegCosts.get(1) * maxPosCosts.get(0));31 return res;32 }33 34 private int numNodes = 1;35 private List<Integer> maxPosCosts = new ArrayList<>();36 private List<Integer> minNegCosts = new ArrayList<>();37}38 39class Solution {40 public long[] placedCoins(int[][] edges, int[] cost) {41 final int n = cost.length;42 long[] ans = new long[n];43 List<Integer>[] tree = new List[n];44 45 for (int i = 0; i < n; i++)46 tree[i] = new ArrayList<>();47 48 for (int[] edge : edges) {49 final int u = edge[0];50 final int v = edge[1];51 tree[u].add(v);52 tree[v].add(u);53 }54 55 dfs(tree, 0, -1, cost, ans);56 return ans;57 }58 59 private ChildCost dfs(List<Integer>[] tree, int u, int prev, int[] cost, long[] ans) {60 ChildCost res = new ChildCost(cost[u]);61 for (final int v : tree[u])62 if (v != prev)63 res.update(dfs(tree, v, u, cost, ans));64 ans[u] = res.maxProduct();65 return res;66 }67}68