Advertisement
rajeshinternshala

Untitled

Apr 10th, 2024
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1.   public static int findTotalCost(int[] arr) {
  2.         // Min heap for keeping track of the minimum elements
  3.         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
  4.         // Max heap for keeping track of the maximum elements
  5.         PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
  6.  
  7.         // Total cost to perform the operations
  8.         int totalCost = 0;
  9.  
  10.         // Add all elements to both heaps
  11.         for (int value : arr) {
  12.             minHeap.add(value);
  13.             maxHeap.add(value);
  14.         }
  15.  
  16.         while (minHeap.size() > 1) {
  17.             // Retrieve and remove the minimum and the maximum elements
  18.             int min = minHeap.poll();
  19.             int max = maxHeap.poll();
  20.  
  21.             // Since we're removing these, we need to also remove the max from minHeap and the min from maxHeap
  22.             minHeap.remove(max);
  23.             maxHeap.remove(min);
  24.  
  25.             // Calculate the cost of the operation
  26.             int sum = min + max;
  27.             int cost = (int) Math.ceil((double) sum / (max - min + 1));
  28.  
  29.             // Add the cost to total cost
  30.             totalCost += cost;
  31.  
  32.             // Add the sum back to both heaps
  33.             minHeap.add(sum);
  34.             maxHeap.add(sum);
  35.         }
  36.  
  37.         // Return the total cost after all operations are performed
  38.         return totalCost;
  39.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement