Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int findTotalCost(int[] arr) {
- TreeMap<Integer, Integer> map = new TreeMap<>();
- for (int num : arr) {
- map.put(num, map.getOrDefault(num, 0) + 1);
- }
- int totalCost = 0;
- while (map.size() > 1 || map.firstEntry().getValue() > 1) {
- int min = map.firstKey();
- int max = map.lastKey();
- // Decrement the count for min and max in the map
- decrementCount(map, min);
- decrementCount(map, max);
- // If min and max are the same and there are no more of such numbers, break
- if (min == max && !map.containsKey(min)) {
- break;
- }
- int sum = min + max;
- int cost = (int) Math.ceil((double) sum / (max - min + 1));
- totalCost += cost;
- // Increment the count for the new sum in the map
- map.put(sum, map.getOrDefault(sum, 0) + 1);
- }
- return totalCost;
- }
- private static void decrementCount(TreeMap<Integer, Integer> map, int num) {
- if (map.get(num) == 1) {
- map.remove(num);
- } else {
- map.put(num, map.get(num) - 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement