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
iis less than3, place1coin. - Otherwise, place an amount of coins equal to the maximum product of cost values assigned to
3 distinct nodesin the subtree of nodei. - If this product is negative, place
0coins.
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code