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
Find Number of Coins to Place in Tree Nodes INPUT Tree Structure (rooted at 0) 0 cost=1 1 cost=3 2 cost=2 3 cost=5 edges: [[0,1],[1,2],[1,3]] cost: [1, 3, 2, 5] ALGORITHM STEPS 1 DFS Traversal Post-order: process children first 2 Collect Subtree Costs Merge costs from children 3 Sort and Select Keep top 3 max, bottom 2 min 4 Calculate Product Max of (top3) vs (min2 * max1) Processing Node 0: Subtree costs: [1,3,2,5] Sorted: [1,2,3,5] Top 3: 5,3,2 Product: 5*3*2 = 30 coin[0]=30 FINAL RESULT Coins Placed on Each Node 0 30 1 30 2 1 3 1 Output Array: [30, 30, 1, 1] Nodes 2,3: subtree < 3 Nodes 0,1: max product Key Insight: To maximize product of 3 costs, keep only 5 values: top 3 maximum and bottom 2 minimum. Max product = max(top1*top2*top3, min1*min2*top1) -- handles negative costs efficiently. Time: O(n log n) for sorting at each node. Space: O(n) for recursion and cost storage. TutorialsPoint - Find Number of Coins to Place in Tree Nodes | DFS with Sorted Selection Approach
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