Using MultiSet and Adhoc Implementation Approach
\n#define ll long long int\nclass Solution {\n    vector<ll>ans;\npublic:\n    multiset<ll,greater<ll>> dfs(ll src,vector<ll>adj[],vector<int>&cost,vector<bool>
```\n#define ll long long int\nclass Solution {\n    vector<ll>ans;\npublic:\n    multiset<ll,greater<ll>> dfs(ll src,vector<ll>adj[],vector<int>&cost,vector<bool>&vis){\n        vis[src]=true;\n        multiset<ll,greater<ll>>mp; // map at this level;\n        for(auto x: adj[src]){\n            if(vis[x]==false){\n                multiset<ll,greater<ll>>temp = dfs(x,adj,cost,vis);\n                for(auto x: temp)\n                    mp.insert(x);\n            }\n        }\n        // at this point of time all it\'s neighbours of src are visited;\n        // Now try to check the size of the \n        mp.insert(cost[src]);\n        ll size = mp.size();\n        if(size<3){\n            ans[src] = 1;\n            return mp;\n        }else{\n            // pick the top 3 distinct coins;\n            auto x = mp.begin();\n            ll first = *x;  x++;\n            ll second = *x; x++;\n            ll third = *x;\n            \n            auto y = mp.rbegin(); // will get the smaller value;\n            ll first2 = *y; y++;\n            ll second2 = *y; y++; \n            \n            ll val = max({first*second*third,first*first2*second2});\n            if(val<0) val = 0;\n            ans[src]=val;\n            if(size<=5){\n                return mp;\n            }else{\n                return {first,second,third,first2,second2};\n            }\n        }\n        return mp;\n    }\n    \n    vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {\n        ll n = cost.size();\n        vector<ll>adj[n];\n        for(auto x: edges){\n            adj[x[0]].push_back(x[1]);\n            adj[x[1]].push_back(x[0]);\n        }\n        ans.resize(n,1);\n        vector<bool>vis(n,false);\n        dfs(0,adj,cost,vis);\n        return ans;\n    }\n};\n```
[]