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
- 45 lines of C++ from the credited upstream file 2920.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 Solution {2 public:3 int maximumPoints(vector<vector<int>>& edges, vector<int>& coins, int k) {4 const int n = coins.size();5 vector<vector<int>> graph(n);6 vector<vector<int>> mem(n, vector<int>(kMaxHalved + 1, -1));7 8 for (const vector<int>& edge : edges) {9 const int u = edge[0];10 const int v = edge[1];11 graph[u].push_back(v);12 graph[v].push_back(u);13 }14 15 return dfs(graph, 0, -1, coins, k, 0, mem);16 }17 18 private:19 static constexpr int kMaxCoin = 10000;20 static constexpr int kMaxHalved = 13; 21 22 int dfs(const vector<vector<int>>& graph, int u, int prev,23 const vector<int>& coins, int k, int halved,24 vector<vector<int>>& mem) {25 26 if (halved > kMaxHalved)27 return 0;28 if (mem[u][halved] != -1)29 return mem[u][halved];30 31 const int val = coins[u] / (1 << halved);32 int takeAll = val - k;33 int takeHalf = floor(val / 2.0);34 35 for (const int v : graph[u]) {36 if (v == prev)37 continue;38 takeAll += dfs(graph, v, u, coins, k, halved, mem);39 takeHalf += dfs(graph, v, u, coins, k, halved + 1, mem);40 }41 42 return mem[u][halved] = max(takeAll, takeHalf);43 }44};45