Skip to content

Practice Find Number of Coins to Place in Tree Nodes

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2973
LeetCode Problem

Find Number of Coins to Place in Tree Nodes

Problem Statement

The tree has undirected edges, is rooted at node 0, and node i has value cost[i]. For each node with fewer than three nodes in its subtree, place one coin. Otherwise find the greatest product of costs of three distinct nodes in its subtree and place that many coins, or zero if the greatest product is negative. Return the coin count for every node.

Source: Find Number of Coins to Place in Tree Nodes on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6]
Output
[120,1,1,1,1,1]

# Example 2

Input
edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2]
Output
[280,140,32,1,1,1,1,1,1]

# Example 3

Input
edges = [[0,1],[0,2]], cost = [1,2,-2]
Output
[0,1,1]

Constraints

2 <= n <= 2 * 10^4
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
cost.length == n
1 <= |cost[i]| <= 10^4
The input is generated such that edges represents a valid tree.

Related LeetCode Problems

Practice more problems similar to Find Number of Coins to Place in Tree Nodes.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.