Advertisement
rajeshinternshala

Untitled

Apr 10th, 2024
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1.     public static int findTotalCost(int[] arr) {
  2.         TreeMap<Integer, Integer> map = new TreeMap<>();
  3.         for (int num : arr) {
  4.             map.put(num, map.getOrDefault(num, 0) + 1);
  5.         }
  6.  
  7.         int totalCost = 0;
  8.  
  9.         while (map.size() > 1 || map.firstEntry().getValue() > 1) {
  10.             int min = map.firstKey();
  11.             int max = map.lastKey();
  12.  
  13.             // Decrement the count for min and max in the map
  14.             decrementCount(map, min);
  15.             decrementCount(map, max);
  16.  
  17.             // If min and max are the same and there are no more of such numbers, break
  18.             if (min == max && !map.containsKey(min)) {
  19.                 break;
  20.             }
  21.  
  22.             int sum = min + max;
  23.             int cost = (int) Math.ceil((double) sum / (max - min + 1));
  24.             totalCost += cost;
  25.  
  26.             // Increment the count for the new sum in the map
  27.             map.put(sum, map.getOrDefault(sum, 0) + 1);
  28.         }
  29.  
  30.         return totalCost;
  31.     }
  32.  
  33.     private static void decrementCount(TreeMap<Integer, Integer> map, int num) {
  34.         if (map.get(num) == 1) {
  35.             map.remove(num);
  36.         } else {
  37.             map.put(num, map.get(num) - 1);
  38.         }
  39.     }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement