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
- 50 lines of Python from the credited upstream file 2973.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 def __init__(self, cost: int):3 self.numNodes = 14 self.maxPosCosts = [cost] if cost > 0 else []5 self.minNegCosts = [cost] if cost < 0 else []6 7 def update(self, childCost: 'ChildCost') -> None:8 self.numNodes += childCost.numNodes9 self.maxPosCosts.extend(childCost.maxPosCosts)10 self.minNegCosts.extend(childCost.minNegCosts)11 self.maxPosCosts.sort(reverse=True)12 self.minNegCosts.sort()13 self.maxPosCosts = self.maxPosCosts[:3]14 self.minNegCosts = self.minNegCosts[:2]15 16 def maxProduct(self) -> int:17 if self.numNodes < 3:18 return 119 if not self.maxPosCosts:20 return 021 res = 022 if len(self.maxPosCosts) == 3:23 res = self.maxPosCosts[0] * self.maxPosCosts[1] * self.maxPosCosts[2]24 if len(self.minNegCosts) == 2:25 res = max(res,26 self.minNegCosts[0] * self.minNegCosts[1] * self.maxPosCosts[0])27 return res28 29 30class Solution:31 def placedCoins(self, edges: list[list[int]], cost: list[int]) -> list[int]:32 n = len(cost)33 ans = [0] * n34 tree = [[] for _ in range(n)]35 36 for u, v in edges:37 tree[u].append(v)38 tree[v].append(u)39 40 def dfs(u: int, prev: int) -> None:41 res = ChildCost(cost[u])42 for v in tree[u]:43 if v != prev:44 res.update(dfs(v, u))45 ans[u] = res.maxProduct()46 return res47 48 dfs(0, -1)49 return ans50