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
- 70 lines of C++ from the credited upstream file 2973.cpp.
- 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 ChildCost {2 public:3 ChildCost(int cost) {4 numNodes = 1;5 if (cost > 0)6 maxPosCosts.push_back(cost);7 else8 minNegCosts.push_back(cost);9 }10 11 void update(ChildCost childCost) {12 numNodes += childCost.numNodes;13 ranges::copy(childCost.maxPosCosts, back_inserter(maxPosCosts));14 ranges::copy(childCost.minNegCosts, back_inserter(minNegCosts));15 ranges::sort(maxPosCosts, greater<int>());16 ranges::sort(minNegCosts);17 maxPosCosts.resize(min(static_cast<int>(maxPosCosts.size()), 3));18 minNegCosts.resize(min(static_cast<int>(minNegCosts.size()), 2));19 }20 21 long maxProduct() {22 if (numNodes < 3)23 return 1;24 if (maxPosCosts.empty())25 return 0;26 long res = 0;27 if (maxPosCosts.size() == 3)28 res = static_cast<long>(maxPosCosts[0]) * maxPosCosts[1] * maxPosCosts[2];29 if (minNegCosts.size() == 2)30 res = max(res, static_cast<long>(minNegCosts[0]) * minNegCosts[1] *31 maxPosCosts[0]);32 return res;33 }34 35 private:36 int numNodes;37 vector<int> maxPosCosts;38 vector<int> minNegCosts;39};40 41class Solution {42 public:43 vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {44 const int n = cost.size();45 vector<long long> ans(n);46 vector<vector<int>> tree(n);47 48 for (const vector<int>& edge : edges) {49 const int u = edge[0];50 const int v = edge[1];51 tree[u].push_back(v);52 tree[v].push_back(u);53 }54 55 dfs(tree, 0, -1, cost, ans);56 return ans;57 }58 59 private:60 ChildCost dfs(const vector<vector<int>>& tree, int u, int prev,61 const vector<int>& cost, vector<long long>& ans) {62 ChildCost res(cost[u]);63 for (const int v : tree[u])64 if (v != prev)65 res.update(dfs(tree, v, u, cost, ans));66 ans[u] = res.maxProduct();67 return res;68 }69};70