C++ Solution || DFS
Code\ncpp []\nclass Solution {\npublic:\n    vector<long long> ans;\n    vector<int> subtreeSize; // To store the size of the subtree for each node\n\n    // DF
# Code\n```cpp []\nclass Solution {\npublic:\n    vector<long long> ans;\n    vector<int> subtreeSize; // To store the size of the subtree for each node\n\n    // DFS to calculate the size of each subtree and calculate the coins for each node\n    vector<long> solve(int node, vector<vector<int>>& child, int par, vector<int>& cost) {\n        vector<long> temp, temp2;\n\n        // Initialize the subtree size for the current node\n        subtreeSize[node] = 1;\n\n        // Traverse all children of the node\n        for (auto c : child[node]) {\n            if (c != par) {\n                // Recurse on the child node and get costs from its subtree\n                temp = solve(c, child, node, cost);\n                for (auto x : temp) {\n                    temp2.push_back(x);\n                }\n                subtreeSize[node] += subtreeSize[c]; // Update the size of the current node\'s subtree\n            }\n        }\n\n        // Include the cost of the current node itself\n        temp2.push_back(cost[node]);\n        sort(temp2.begin(), temp2.end());\n\n        // Determine the number of coins to place at the current node\n        if (subtreeSize[node] < 3) {\n            // If the size of the subtree is less than 3, place 1 coin\n            ans[node] = 1;\n        } else {\n            // Otherwise, find the maximum product of 3 distinct nodes\n            int n = temp2.size();\n            long long op1 = static_cast<long long>(temp2[n - 1]) * static_cast<long long>(temp2[n - 2]) * static_cast<long long>(temp2[n - 3]); // Product of 3 largest\n            long long op2 = static_cast<long long>(temp2[n - 1]) * static_cast<long long>(temp2[0]) * static_cast<long long>(temp2[1]); // Product of largest and 2 smallest\n\n            // Use explicit std::max calls to determine the maximum value\n            ans[node] = std::max(0LL, std::max(op1, op2)); // If negative, make it 0\n        }\n\n        // Return a subset of the collected costs for further calculations\n        if (temp2.size() <= 5) {\n            return temp2;\n        } else {\n            return {temp2.back(), temp2[temp2.size() - 2], temp2[temp2.size() - 3], temp2[0], temp2[1]};\n        }\n    }\n\n    vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {\n        int n = cost.size();\n        vector<vector<int>> child(n);\n\n        // Build the adjacency list from the edges\n        for (const auto& e : edges) {\n            child[e[0]].push_back(e[1]);\n            child[e[1]].push_back(e[0]); // Since it\'s an undirected tree\n        }\n\n        ans.resize(n);\n        subtreeSize.resize(n);\n        solve(0, child, -1, cost);\n        return ans;\n    }\n};\n\n```
['C++']