Find Number of Coins to Place in Tree Nodes - Problem

You are given an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. 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 integer array cost of length n, where cost[i] is the cost assigned to the ith node.

You need to place some coins on every node of the tree. The number of coins to be placed at node i can be calculated as:

  • If size of the subtree of node i is less than 3, place 1 coin.
  • Otherwise, place an amount of coins equal to the maximum product of cost values assigned to 3 distinct nodes in the subtree of node i.
  • If this product is negative, place 0 coins.

Return an array coin of size n such that coin[i] is the number of coins placed at node i.

Input & Output

Example 1 — Basic Tree
$ Input: edges = [[0,1],[1,2],[1,3]], cost = [1,3,2,5]
Output: [30,30,1,1]
💡 Note: Node 0 subtree {0,1,2,3} has max product 3×2×5=30. Node 1 subtree {1,2,3} has max product 3×2×5=30. Nodes 2,3 have subtree size <3, so get 1 coin each.
Example 2 — Negative Values
$ Input: edges = [[0,1],[0,2]], cost = [-2,3,-1]
Output: [6,1,1]
💡 Note: Node 0 subtree {0,1,2} has costs [-2,3,-1]. Max product is (-2)×3×(-1)=6. Nodes 1,2 have subtree size 1, so get 1 coin each.
Example 3 — Single Node
$ Input: edges = [], cost = [5]
Output: [1]
💡 Note: Only one node with subtree size 1 < 3, so it gets 1 coin.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • edges.length == n - 1
  • 0 ≤ ai, bi < n
  • -104 ≤ cost[i] ≤ 104

Visualization

Tap to expand
Tree Coin Placement ProblemInput Tree0cost=11cost=32cost=23cost=5AnalysisNode 0 subtree: {0,1,2,3}Costs: [1,3,2,5]Max product: 3×2×5 = 30Node 1 subtree: {1,2,3}Costs: [3,2,5]Max product: 3×2×5 = 30Nodes 2,3: subtree size < 3Each gets 1 coinOutputCoins[30,30,1,1]Node 0: 30 coinsNode 1: 30 coinsNode 2: 1 coinNode 3: 1 coinRule: size < 3 → 1 coin, else max product of 3 distinct costs (0 if negative)
Understanding the Visualization
1
Input Tree
Tree structure with cost values on each node
2
Subtree Analysis
For each node, analyze its subtree to determine coin placement
3
Coin Placement
Place coins based on subtree size and maximum product
Key Takeaway
🎯 Key Insight: Use DFS to collect subtree costs, then sort to efficiently find maximum product of any 3 values
Asked in
Google 15 Amazon 12 Meta 8
8.5K Views
Medium Frequency
~35 min Avg. Time
234 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