Maximum Distinct Elements (medium)
Problem Statement
Given an array of numbers and a number ‘K’, we need to remove ‘K’ numbers from the array such that we are left with maximum distinct numbers.
Example 1:
Input: [7, 3, 5, 8, 5, 3, 3], and K=2
Output: 3
Explanation: We can remove two occurrences of 3 to be left with 3 distinct numbers [7, 3, 8], we have to skip 5 because it is not distinct and appeared twice.
Another solution could be to remove one instance of '5' and '3' each to be left with three distinct numbers [7, 5, 8], in this case, we have to skip 3 because it appeared twice.
Example 2:
Input: [3, 5, 12, 11, 12], and K=3
Output: 2
Explanation: We can remove one occurrence of 12, after which all numbers will become distinct. Then we can delete any two numbers which will leave us 2 distinct numbers in the result.
Example 3:
Input: [1, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5], and K=2
Output: 3
Explanation: We can remove one occurrence of '4' to get three distinct numbers.
Try it yourself
Try solving this question here:
import java.util.*;class MaximumDistinctElements {public static int findMaximumDistinctElements(int[] nums, int k) {// TODO: Write your code herereturn -1;}public static void main(String[] args) {int result = MaximumDistinctElements.findMaximumDistinctElements(new int[] { 7, 3, 5, 8, 5, 3, 3 }, 2);System.out.println("Maximum distinct numbers after removing K numbers: " + result);result = MaximumDistinctElements.findMaximumDistinctElements(new int[] { 3, 5, 12, 11, 12 }, 3);System.out.println("Maximum distinct numbers after removing K numbers: " + result);result = MaximumDistinctElements.findMaximumDistinctElements(new int[] { 1, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5 }, 2);System.out.println("Maximum distinct numbers after removing K numbers: " + result);}}
Solution
This problem follows the Top ‘K’ Numbers pattern, and shares similarities with Top ‘K’ Frequent Numbers.
We can follow a similar approach as discussed in Top ‘K’ Frequent Numbers problem:
- First, we will find the frequencies of all the numbers.
- Then, push all numbers that are not distinct (i.e., have a frequency higher than one) in a Min Heap based on their frequencies. At the same time, we will keep a running count of all the distinct numbers.
- Following a greedy approach, in a stepwise fashion, we will remove the least frequent number from the heap (i.e., the top element of