DFS + sort solution
Code\n\n#define ll long long\nclass Solution {\npublic:\n    \n    vector<ll> dfs(int x, vector<vector<pair<int, int> >> &adj, vector<int> &vis, vector<ll> &ans
# Code\n```\n#define ll long long\nclass Solution {\npublic:\n    \n    vector<ll> dfs(int x, vector<vector<pair<int, int> >> &adj, vector<int> &vis, vector<ll> &ans, vector<int>& cost){\n        vis[x] = 1;\n        \n        vector<ll> v{cost[x]};\n        for(auto it: adj[x]){\n            int c = it.first;\n            int y = it.second;\n            if(vis[y]==0){\n                vector<ll> res = dfs(y, adj, vis, ans, cost);\n                v.insert(v.end(), res.begin(), res.end());\n            }\n        }\n        \n        sort(v.begin(), v.end(), greater());\n\n        // keep 3 max and 2 min\n        if(v.size() > 5){\n            vector<ll> temp(v.begin(), v.begin()+3);\n            temp.push_back(v.back());\n            v.pop_back();\n            temp.push_back(v.back());\n            v = temp;\n        }\n        \n        if(v.size() < 3){\n            ans[x] = 1;\n        }else{\n            int n = v.size();\n            ll val = max(v[0] * v[1] * v[2], v[0] * v[n-1] * v[n-2]);\n            if(val>0) ans[x] = val;\n        }\n        \n        return v;\n    }\n    \n    vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {\n        int n = cost.size();\n        vector<vector<pair<int, int> >> adj(n);\n        \n        for(auto edge: edges){\n            adj[edge[0]].push_back({cost[edge[1]], edge[1]});\n            adj[edge[1]].push_back({cost[edge[0]], edge[0]});\n        }\n        \n        vector<int> vis(n, 0);\n        vector<ll> ans(n, 0);\n        \n        dfs(0, adj, vis, ans, cost);\n        \n        return ans;\n    }\n};\n```
['C++']