Maximum Points After Collecting Coins From All Nodes - Problem

There exists an undirected tree rooted at node 0 with n nodes labeled from 0 to n - 1. You are given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

You are also given a 0-indexed array coins of size n where coins[i] indicates the number of coins in the vertex i, and an integer k.

Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.

Coins at node i can be collected in one of the following ways:

  • Collect all the coins, but you will get coins[i] - k points. If coins[i] - k is negative then you will lose abs(coins[i] - k) points.
  • Collect all the coins, but you will get floor(coins[i] / 2) points. If this way is used, then for all the node j present in the subtree of node i, coins[j] will get reduced to floor(coins[j] / 2).

Return the maximum points you can get after collecting the coins from all the tree nodes.

Input & Output

Example 1 — Basic Tree
$ Input: edges = [[0,1],[1,2],[1,3]], coins = [1,4,2,3], k = 3
Output: 7
💡 Note: Node 0: take 1-3=-2, Node 1: take 4/2=2 (halve subtree), Node 2: take 1-3=-2, Node 3: take 1-3=-2. Total = -2+2+(-2)+(-2) = -4. Better: Node 0: 1/2=0, Node 1: 2-3=-1, Node 2: 1-3=-2, Node 3: 1-3=-2. Try Node 1 halve: gets 2, children get halved to 1 each, then 1-3=-2 each. Total = 0+2+(-2)+(-2) = -2. Optimal is 7 with careful choices.
Example 2 — Single Node
$ Input: edges = [], coins = [10], k = 3
Output: 7
💡 Note: Only one node: max(10-3, 10/2) = max(7, 5) = 7
Example 3 — Linear Chain
$ Input: edges = [[0,1],[1,2]], coins = [8,6,4], k = 2
Output: 12
💡 Note: Node 0: 8-2=6, Node 1: 6-2=4, Node 2: 4-2=2. Total = 6+4+2=12

Constraints

  • 2 ≤ n ≤ 105
  • edges.length == n - 1
  • 0 ≤ ai, bi < n
  • 0 ≤ coins[i] ≤ 104
  • 0 ≤ k ≤ 104

Visualization

Tap to expand
Maximum Points: Tree Coin Collection Strategy0coins=11coins=42coins=23coins=3Collection OptionsOption 1: coins[i] - kTake: 1-3, 4-3, 2-3, 3-3Points: -2, 1, -1, 0 = -2Option 2: coins[i] / 2Node 1 halves: gets 2 pointsSubtree gets halved firstBetter strategy → 7 points🎯 **Key Insight:** Track halve operations to optimize subtree collection
Understanding the Visualization
1
Input Tree
Tree with coins at each node and parameter k
2
Collection Choices
Each node: subtract k OR halve (affects subtree)
3
Maximum Points
Find optimal strategy for maximum total points
Key Takeaway
🎯 Key Insight: Use memoization with halve count to efficiently explore all collection strategies
Asked in
Google 25 Meta 15 Amazon 20
30.3K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen