Track the three largest and the two smallest [JAVA]
\n# Code\n\nclass Solution {\n    public long[] placedCoins(int[][] edges, int[] cost) {\n        int n = cost.length;\n        List<Integer>[] adjs = new List[
\n# Code\n```\nclass Solution {\n    public long[] placedCoins(int[][] edges, int[] cost) {\n        int n = cost.length;\n        List<Integer>[] adjs = new List[n];\n        for (int i = 0; i < n; i++) {\n            adjs[i] = new ArrayList<>();\n        }\n        for (int[] edge : edges) {\n            adjs[edge[0]].add(edge[1]);\n            adjs[edge[1]].add(edge[0]);\n        }\n\n        long[] ans = new long[n];\n        traverse(0, -1, cost, adjs, ans);\n        return ans;\n    }\n\n    private List<Long> traverse(int node, int parent, int[] cost, List<Integer>[] adjs, long[] ans) {\n        List<Long> sortedCosts = new ArrayList<>();\n        sortedCosts.add((long) cost[node]);\n        for (int adj : adjs[node]) {\n            if (adj == parent) {\n                continue;\n            }\n            sortedCosts.addAll(traverse(adj, node, cost, adjs, ans));\n        }\n\n        if (sortedCosts.size() < 3) {\n            ans[node] = 1;\n            return sortedCosts;\n        }\n\n        Collections.sort(sortedCosts);\n\n        int s = sortedCosts.size();\n        // We consider two possible options: the product of the 1st, 2nd, and 3rd largest elements,\n        // and the product of the 1st largest element and the 1st and 2nd smallest elements.\n        // We choose the larger product as maxProduct.\n        long largest = Math.max(sortedCosts.get(s - 1) * sortedCosts.get(0) * sortedCosts.get(1),\n                                sortedCosts.get(s - 1) * sortedCosts.get(s - 2) *  sortedCosts.get(s - 3));\n        ans[node] = largest > 0 ? largest : 0;\n\n        if (sortedCosts.size() <= 5) {\n            return sortedCosts;\n        }\n\n        return List.of(sortedCosts.get(0), sortedCosts.get(1), sortedCosts.get(s -  3), sortedCosts.get(s - 2), sortedCosts.get(s - 1));\n    }\n}\n```
['Java']