Min Heap and Max Heap Java for tracking the 3 largest and 2 smallest
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        KthMinKthMax kthMinKthMax = new KthMinKthMax(2, 3);\n        kthMinKthMax.add(cost[node]);\n        for (int adj : adjs[node]) {\n            if (adj == parent) {\n                continue;\n            }\n            for (long c : traverse(adj, node, cost, adjs, ans)) {\n                kthMinKthMax.add(c);\n            }\n        }\n\n        List<Long> sortedCosts = kthMinKthMax.getAll();\n        if (sortedCosts.size() < 3) {\n            ans[node] = 1;\n            return sortedCosts;\n        }\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        return sortedCosts;\n    }\n\n    static class KthMinKthMax {\n        int min;\n        int max;\n        PriorityQueue<Long> minHeap;\n        PriorityQueue<Long> maxHeap;\n\n        KthMinKthMax(int min, int max) {\n            this.min = min;\n            this.max = max;\n            this.maxHeap = new PriorityQueue<>(min, Comparator.reverseOrder());\n            this.minHeap = new PriorityQueue<>(max);\n        }\n\n        public void add(long num) {\n            minHeap.add(num);\n            if (minHeap.size() > max) {\n                maxHeap.add(minHeap.remove());\n                if (maxHeap.size() > min) {\n                    maxHeap.remove();\n                }\n            }\n        }\n\n        public List<Long> getAll() {\n            List<Long> list = new ArrayList<>(minHeap);\n            list.addAll(maxHeap);\n            Collections.sort(list);\n            return list;\n        }\n    }\n}\n```
['Java']