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 arraycoinof sizensuch thatcoin[i]is the number of coins placed at nodei.

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]Explanation: For node 0 place 6*5*4=120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them.

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]Explanation: The coins placed on each node are:- Place 8*7*5=280 coins on node 0.- Place 7*5*4=140 coins on node 1.- Place 8*2*2=32 coins on node 2.- All other nodes are leaves with subtree of size 1, place 1 coin on each of them.

Input: edges =[[0,1],[0,2]], cost =[1,2,-2]Output: [0,1,1]Explanation: Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is2*1*-2=-4. Hence place 0 coins on node 0.
For each node, we need to find the maximum product of any 3 costs in its subtree. We can use DFS to collect the top 3 largest and bottom 2 smallest costs in the subtree (to handle negative products). For each node, if the subtree size is less than 3, place 1 coin. Otherwise, compute the maximum product of any 3 costs (either the product of the top 3 largest or the product of the 2 smallest and the largest, to handle negatives). If the product is negative, place 0 coins.
classSolution {
funplacedCoins(edges: Array<IntArray>, cost: IntArray): IntArray {
val n = cost.size
val g = Array(n) { mutableListOf<Int>() }
for (e in edges) {
g[e[0]].add(e[1])
g[e[1]].add(e[0])
}
val ans = IntArray(n)
fundfs(u: Int, p: Int): List<Int> {
val vals = mutableListOf(cost[u])
for (v in g[u]) if (v != p) vals.addAll(dfs(v, u))
if (vals.size < 3) ans[u] = 1else {
vals.sort()
val n = vals.size
val prod1 = vals[n-1].toLong() * vals[n-2] * vals[n-3]
val prod2 = vals[0].toLong() * vals[1] * vals[n-1]
val prod = maxOf(prod1, prod2)
ans[u] = if (prod < 0) 0else prod.toInt()
}
return vals
}
dfs(0, -1)
return ans
}
}