Skip to content

Commit 0ca13d8

Browse files
authored
Create Reduction Operations to Make the Array Elements Equal.java
1 parent 7cb5fe6 commit 0ca13d8

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public int reductionOperations(int[] nums) {
3+
Map<Integer, Integer> map = new HashMap<>();
4+
for (int i = 0; i < nums.length; i++) {
5+
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
6+
}
7+
PriorityQueue<KeyEntry> pq = new PriorityQueue<>(new Comparator<>(){
8+
public int compare(KeyEntry k1, KeyEntry k2) {
9+
return k2.key - k1.key;
10+
}
11+
});
12+
for (Integer key : map.keySet()) {
13+
pq.add(new KeyEntry(key, map.get(key)));
14+
}
15+
int numOfSteps = 0;
16+
while (pq.size() > 1) {
17+
KeyEntry largest = pq.poll();
18+
KeyEntry secondLargest = pq.poll();
19+
secondLargest.val += largest.val;
20+
pq.add(secondLargest);
21+
numOfSteps += largest.val;
22+
}
23+
return numOfSteps;
24+
}
25+
}
26+
27+
class KeyEntry {
28+
int key;
29+
int val;
30+
31+
public KeyEntry(int key, int val) {
32+
this.key = key;
33+
this.val = val;
34+
}
35+
}

0 commit comments

Comments
 (0)