Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int findTotalCost(int[] arr) {
- // Min heap for keeping track of the minimum elements
- PriorityQueue<Integer> minHeap = new PriorityQueue<>();
- // Max heap for keeping track of the maximum elements
- PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
- // Total cost to perform the operations
- int totalCost = 0;
- // Add all elements to both heaps
- for (int value : arr) {
- minHeap.add(value);
- maxHeap.add(value);
- }
- while (minHeap.size() > 1) {
- // Retrieve and remove the minimum and the maximum elements
- int min = minHeap.poll();
- int max = maxHeap.poll();
- // Since we're removing these, we need to also remove the max from minHeap and the min from maxHeap
- minHeap.remove(max);
- maxHeap.remove(min);
- // Calculate the cost of the operation
- int sum = min + max;
- int cost = (int) Math.ceil((double) sum / (max - min + 1));
- // Add the cost to total cost
- totalCost += cost;
- // Add the sum back to both heaps
- minHeap.add(sum);
- maxHeap.add(sum);
- }
- // Return the total cost after all operations are performed
- return totalCost;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement