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