<p>You are given an <strong>undirected</strong> tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>, and rooted at node <code>0</code>. You are given a 2D integer array <code>edges</code> of length <code>n - 1</code>, where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>

<p>You are also given a <strong>0-indexed</strong> integer array <code>cost</code> of length <code>n</code>, where <code>cost[i]</code> is the <strong>cost</strong> assigned to the <code>i<sup>th</sup></code> node.</p>

<p>You need to place some coins on every node of the tree. The number of coins to be placed at node <code>i</code> can be calculated as:</p>

<ul>
	<li>If size of the subtree of node <code>i</code> is less than <code>3</code>, place <code>1</code> coin.</li>
	<li>Otherwise, place an amount of coins equal to the <strong>maximum</strong> product of cost values assigned to <code>3</code> distinct nodes in the subtree of node <code>i</code>. If this product is <strong>negative</strong>, place <code>0</code> coins.</li>
</ul>

<p>Return <em>an array </em><code>coin</code><em> of size </em><code>n</code><em> such that </em><code>coin[i]</code><em> is the number of coins placed at node </em><code>i</code><em>.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/11/09/screenshot-2023-11-10-012641.png" style="width: 600px; height: 233px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6]
<strong>Output:</strong> [120,1,1,1,1,1]
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/11/09/screenshot-2023-11-10-012614.png" style="width: 800px; height: 374px;" />
<pre>
<strong>Input:</strong> 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]
<strong>Output:</strong> [280,140,32,1,1,1,1,1,1]
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/11/09/screenshot-2023-11-10-012513.png" style="width: 300px; height: 277px;" />
<pre>
<strong>Input:</strong> edges = [[0,1],[0,2]], cost = [1,2,-2]
<strong>Output:</strong> [0,1,1]
<strong>Explanation:</strong> 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 is 2 * 1 * -2 = -4. Hence place 0 coins on node 0.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>edges.length == n - 1</code></li>
	<li><code>edges[i].length == 2</code></li>
	<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>
	<li><code>cost.length == n</code></li>
	<li><code>1 &lt;= |cost[i]| &lt;= 10<sup>4</sup></code></li>
	<li>The input is generated such that <code>edges</code> represents a valid tree.</li>
</ul>

from collections import defaultdict as dd
class Solution:
    def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]:
        N=len(cost)
        nbrs = dd(lambda : dd(lambda : False))
        all_node_part_of_edge = set()
        for a,b in edges:
            nbrs[a][b] = True
            nbrs[b][a] = True
            all_node_part_of_edge.add(a)
            all_node_part_of_edge.add(b)
        # ###############################################
        #  do a bfs from root and store the nodes at a given depth
        # ##############################################
        periphery = set([0])
        parent = dd(lambda : None)
        vis = dd(lambda : False)
        TREE_DEPTH= 0
        node_at_depth = dd(lambda : set())
        while(True):
            if(len(periphery) == 0 ):
                break
            periphery1 = set()
            TREE_DEPTH+=1
            for node1 in periphery:
                vis[node1] = True
                node_at_depth[TREE_DEPTH].add(node1)
                for node2 in nbrs[node1]:
                    if(not(vis[node2] or node2 in periphery)):
                        periphery1.add(node2)
                        parent[node2] = node1
            periphery = periphery1

        # ###########################################
        # Traverse tree from highest depth to lowest depth 
        # ###########################################
        # At each level/depth , for each node on the level calculate:-
        # - coin for that node - node1 base on logic specified in P.S. 
        # - NOte: We only need smallest two , largest three cost of the subtree rooted at node1 . Call this information parentInfo[node1] 
        # - append parentsInfo for parent[node1]
        # ############################################
        parentsInfo = dd(lambda : [])
        coin = dd(lambda : None)
        depth = TREE_DEPTH
        while(True):
            periphery = node_at_depth[depth]
            if(len(periphery) == 0):
                break
            for node1 in periphery:
                node2 = parent[node1]
                parentsInfo[node1].append((cost[node1],node1))
                parentsInfoNode1 = parentsInfo[node1]  
                costs1 = list(sorted(parentsInfoNode1,key = lambda x: x[0]))
                # calculate coin for node1
                _coin = None
                if(len(costs1)>=5):
                    # NOte: We only need smallest two , largest three cost of the subtree rooted at node1 to calculate coin[node1]
                    costs1 = [costs1[0] , costs1[1], costs1[-3], costs1[-2], costs1[-1] ]
                    x1=   costs1[0][0] * costs1[1][0] * costs1[-1][0]
                    x2= costs1[-3][0] * costs1[-2][0] * costs1[-1][0]
                    _coin = max(x1,x2,0)
                elif(len(costs1)>=4):
                    # NOte: We only need smallest two , largest three cost of the subtree rooted at node1 to calculate coin[node1]
                    costs1 = [costs1[0] , costs1[1], costs1[2] , costs1[3]]
                    
                    x1=   costs1[0][0] * costs1[1][0] * costs1[-1][0]
                    x2= costs1[-3][0] * costs1[-2][0] * costs1[-1][0]
                    _coin = max(x1,x2,0)
                elif(len(costs1)>=3):
                    # NOte: We only need smallest two , largest three cost of the subtree rooted at node1 to calculate coin[node1]
                    costs1 = [costs1[0] , costs1[1], costs1[2] ]
                    _coin = max(costs1[0][0] * costs1[1][0] * costs1[2][0] , 0)
                else:
                    _coin = 1
                    costs1 = costs1
                coin[node1] = _coin 
                if(node2 is not None):
                    # - append parentsInfo for parent[node1]
                    parentsInfo[node2].extend(costs1)
            depth+=-1
        return [coin[i] for i in range(N)]
1971