Problem solution · C++

Find Number of Coins to Place in Tree Nodes

Find Number of Coins to Place in Tree Nodes: a C++ solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
70 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind Number of Coins to Place in Tree Nodes · C++C++
Use this to learn the idea, then write your own version.
class ChildCost { public:  ChildCost(int cost) {    numNodes = 1;    if (cost > 0)      maxPosCosts.push_back(cost);    else      minNegCosts.push_back(cost);  }   void update(ChildCost childCost) {    numNodes += childCost.numNodes;    ranges::copy(childCost.maxPosCosts, back_inserter(maxPosCosts));    ranges::copy(childCost.minNegCosts, back_inserter(minNegCosts));    ranges::sort(maxPosCosts, greater<int>());    ranges::sort(minNegCosts);    maxPosCosts.resize(min(static_cast<int>(maxPosCosts.size()), 3));    minNegCosts.resize(min(static_cast<int>(minNegCosts.size()), 2));  }   long maxProduct() {    if (numNodes < 3)      return 1;    if (maxPosCosts.empty())      return 0;    long res = 0;    if (maxPosCosts.size() == 3)      res = static_cast<long>(maxPosCosts[0]) * maxPosCosts[1] * maxPosCosts[2];    if (minNegCosts.size() == 2)      res = max(res, static_cast<long>(minNegCosts[0]) * minNegCosts[1] *                         maxPosCosts[0]);    return res;  }  private:  int numNodes;  vector<int> maxPosCosts;  vector<int> minNegCosts;}; class Solution { public:  vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {    const int n = cost.size();    vector<long long> ans(n);    vector<vector<int>> tree(n);     for (const vector<int>& edge : edges) {      const int u = edge[0];      const int v = edge[1];      tree[u].push_back(v);      tree[v].push_back(u);    }     dfs(tree, 0, /*prev=*/-1, cost, ans);    return ans;  }  private:  ChildCost dfs(const vector<vector<int>>& tree, int u, int prev,                const vector<int>& cost, vector<long long>& ans) {    ChildCost res(cost[u]);    for (const int v : tree[u])      if (v != prev)        res.update(dfs(tree, v, u, cost, ans));    ans[u] = res.maxProduct();    return res;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗