-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_9_Maximum_Distinct_Elements.java
More file actions
50 lines (40 loc) · 1.7 KB
/
Problem_9_Maximum_Distinct_Elements.java
File metadata and controls
50 lines (40 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Top_K_Elements;
// Problem Statement: Maximum Distinct Elements (medium)
// LeetCode Question:
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class Problem_9_Maximum_Distinct_Elements {
public int findMaximumDistinctElements(int[] nums, int k) {
int distinctElementsCount = 0;
if (nums.length <= k)
return distinctElementsCount;
// find the frequency of each number
Map<Integer, Integer> numFrequencyMap = new HashMap<>();
for (int i : nums)
numFrequencyMap.put(i, numFrequencyMap.getOrDefault(i, 0) + 1);
PriorityQueue<Map.Entry<Integer, Integer>> minHeap =
new PriorityQueue<Map.Entry<Integer, Integer>>(
(e1, e2) -> e1.getValue() - e2.getValue());
// insert all numbers with frequency greater than '1' into the min-heap
for (Map.Entry<Integer, Integer> entry : numFrequencyMap.entrySet()) {
if (entry.getValue() == 1)
distinctElementsCount++;
else
minHeap.add(entry);
}
// following a greedy approach, try removing the least frequent numbers first from
// the min-heap
while (k > 0 && !minHeap.isEmpty()) {
Map.Entry<Integer, Integer> entry = minHeap.poll();
// to make an element distinct, we need to remove all of its occurrences except one
k -= entry.getValue() - 1;
if (k >= 0)
distinctElementsCount++;
}
// if k > 0, this means we have to remove some distinct numbers
if (k > 0)
distinctElementsCount -= k;
return distinctElementsCount;
}
}