DFS | Explained
Code\n\n#define ll long long\n\nclass Solution {\npublic:\n    // Helper function to perform depth-first search and compute the modified array\n    vector<ll> f
# Code\n```\n#define ll long long\n\nclass Solution {\npublic:\n    // Helper function to perform depth-first search and compute the modified array\n    vector<ll> func(int idx, int par, vector<int>& cost, vector<int> adj[], vector<ll> &ans) {\n        // Initialize the vector with the cost of the current node\n        vector<ll> ret = {(ll)cost[idx]}; \n        \n        // Iterate through adjacent nodes\n        for (auto &neighbor : adj[idx]) {\n            // Skip if the neighbor is the parent (to avoid going back in the tree)\n            if (neighbor == par) continue;\n            \n            // Recursively call the function for the neighbor and merge the result into \'ret\'\n            vector<ll> v = func(neighbor, idx, cost, adj, ans); \n            ret.insert(ret.end(), v.begin(), v.end());\n        } \n        \n        // Calculate the size of the \'ret\' vector\n        int sz = ret.size();\n        // If the size is less than 3, return \'ret\' as is\n        if (sz < 3) return ret; \n\n        // Initialize variables to find the 3 largest and 2 smallest values in \'ret\'\n        ll a, b, c, y, z;\n        a = b = c = LLONG_MIN, y = z = LLONG_MAX;\n\n        // Iterate through \'ret\' to find the largest and smallest values\n        for(auto &value : ret){\n            if(value > a) c = b, b = a, a = value;\n            else if(value > b) c = b, b = value;\n            else if(value > c) c = value;\n\n            if(value < z) y = z, z = value; \n            else if(value < y) y = value;\n        }  \n\n        // Calculate the value for \'ans[idx]\' based on the largest and second-largest values\n        ans[idx] = max(0ll, a * max(b*c, y*z)); \n\n        // If the size is less than or equal to 5, return \'ret\' as is\n        if(sz <= 5) return ret; \n\n        // Return a vector containing the largest 3 and smallest 2 values from \'ret\'\n        return {a, b, c, y, z};\n    }\n\n    // Main function to initialize adjacency list and call the helper function\n    vector<ll> placedCoins(vector<vector<int>>& edges, vector<int>& cost) {\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n\n        int n = cost.size();\n        vector<int> adj[n];\n        \n        // Constructing the adjacency list from the given edges\n        for (auto &x : edges) {\n            adj[x[0]].push_back(x[1]);\n            adj[x[1]].push_back(x[0]);\n        }\n\n        // Initialize the answer vector with default values\n        vector<ll> ans(n, 1);\n        \n        // Call the helper function starting from the root node (0)\n        func(0, -1, cost, adj, ans); \n\n        // Return the final modified array\n        return ans;\n    }\n};\n\n```
['Tree', 'Depth-First Search', 'Sorting', 'C++']