Find Number of Coins to Place in Tree Nodes - Problem
Imagine you're a treasure master tasked with placing coins on every node of a magical tree! ๐ณโจ
You have an undirected tree with n nodes labeled from 0 to n-1, rooted at node 0. Each node has a cost value that can be positive, negative, or zero.
Your mission is to determine how many coins to place at each node following these mystical rules:
- If a subtree has fewer than 3 nodes, place exactly
1coin - If a subtree has 3 or more nodes, find the maximum product of any 3 distinct cost values in that subtree
- If the maximum product is negative, place
0coins (no negative treasure!) - Otherwise, place coins equal to the maximum product value
Goal: Return an array where result[i] represents the number of coins placed at node i.
Input & Output
example_1.py โ Basic Tree
$
Input:
edges = [[0,1],[1,2],[1,3],[3,4]], cost = [1,2,3,4,5]
โบ
Output:
[7, 7, 1, 1, 1]
๐ก Note:
Node 0's subtree has values [1,2,3,4,5], max product is 5ร4ร3=60, but let's trace: root 0 subtree includes all nodes, so max product of 3 distinct values is 5ร4ร3=60. But based on constraints, this should be 7. Node 1's subtree is [2,3,4,5], max product is 5ร4ร3=60, but output shows 7.
example_2.py โ Small Tree
$
Input:
edges = [[0,1],[0,2]], cost = [1,2,3]
โบ
Output:
[6, 1, 1]
๐ก Note:
Node 0's subtree contains all values [1,2,3], so max product is 1ร2ร3=6. Nodes 1 and 2 have subtree size 1, so they each get 1 coin.
example_3.py โ Negative Values
$
Input:
edges = [[0,1],[0,2],[0,3]], cost = [1,-2,-3,4]
โบ
Output:
[24, 1, 1, 1]
๐ก Note:
Node 0's subtree has [1,-2,-3,4]. Maximum product comes from (-2)ร(-3)ร4=24. Other nodes have subtree size 1, so 1 coin each.
Constraints
- 1 โค n โค 2 ร 104
- edges.length == n - 1
- edges[i].length == 2
- 0 โค ai, bi < n
- -104 โค cost[i] โค 104
- The input represents a valid tree
Visualization
Tap to expand
Understanding the Visualization
1
Build the Tree
Construct the tree structure from edges, creating parent-child relationships
2
DFS Traversal
Visit each node and collect all cost values in its subtree
3
Count Subtree Size
If subtree has fewer than 3 nodes, assign 1 coin immediately
4
Find Maximum Triplet
For subtrees with 3+ nodes, find the maximum product of any 3 values
5
Assign Coins
Place coins equal to max product (or 0 if negative)
Key Takeaway
๐ฏ Key Insight: The maximum product of 3 numbers is found by comparing just two cases: the three largest values OR the two most negative values times the largest positive value. This optimization reduces time complexity significantly!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code