Maximum distinct elements after removing k elements - GeeksforGeeks

17 Feb, 2022
Given an array arr[] containing n elements. The problem is to find the maximum number of distinct elements (non-repeating) after removing k elements from the array. Note: 1 <= k <= n.Examples: 
Input : arr[] = {5, 7, 5, 5, 1, 2, 2}, k = 3
Output : 4
Remove 2 occurrences of element 5 and
1 occurrence of element 2.

Input : arr[] = {1, 2, 3, 4, 5, 6, 7}, k = 5
Output : 2

Input : arr[] = {1, 2, 2, 2}, k = 1
Output : 1
Approach: Following are the steps: 
1. Make a multi set from the given array.
2. During making this multiset check if the current element is present or not in multiset, if it is already present then simply reduce the k value and donot insert in the multiset.
3. If k becomes 0 then simply just put values in multiset.
4. After traversing the whole given array, 
       a) if k is not equal to zero then it means the multiset is consist of only unique elements and we have to remove any of the k elements from the multiset to make k=0, so in this case the answer will be size of multiset minus k value at that time.
        b) if k is equal to zero then it means there may be duplicate values present in the multiset so put all the values in a set and the size of this set will be the number of distinct elements after removing k elements
C++
Java
Javascript
// CPP implementation of the above approach#include <bits/stdc++.h>using namespace std;   // function to find maximum distinct elements// after removing k elementsint maxDistinctNum(int a[], int n, int k){  int i;  multiset<int> s;  // making multiset from given array        for(i=0;i<n;i++){            if(s.find(a[i])==s.end()||k==0)            s.insert(a[i]);            else            {                k--;            }        }           if(k!=0)        return s.size()-k;        else{            set<int> st;            for(auto it:s){                st.insert(it);            }            return st.size();        }} // Driver Codeint main(){    int arr[] = { 5, 7, 5, 5, 1, 2, 2 };    int n = sizeof(arr) / sizeof(arr[0]);    int k = 3;       // Function Call    cout << "Maximum distinct elements = "         << maxDistinctNum(arr, n, k);    return 0;}
// Java implementation of the// above approachimport java.util.*;class GFG{     // Function to find maximum// distinct elements after// removing k elementsstatic int maxDistinctNum(int arr[],                          int n, int k){  HashMap<Integer,          Integer> numToFreq = new HashMap<>();   // Build frequency map  for(int i = 0 ; i < n ; i++)  {    numToFreq.put(arr[i],    numToFreq.getOrDefault(arr[i], 0) + 1);  }   int result = 0;   // Min-heap  PriorityQueue<Integer> minHeap =                new PriorityQueue<Integer>();   // Add all number with freq=1 to  // result and push others to minHeap  for(Map.Entry<Integer,                Integer> p : numToFreq.entrySet())  {    if(p.getValue() == 1)      ++result;    else      minHeap.add(p.getValue());  }   // Perform k operations  while(k != 0 && !minHeap.isEmpty())  {    // Pop the top() element    Integer t = minHeap.poll();         // Increment Result    if(t == 1)    {      ++result;    }     // Reduce t and k    // Push it again    else    {      --t;      --k;      minHeap.add(t);    }  }   // Return result  return result;} // Driver codepublic static void main(String[] args){         int arr[] = {5, 7, 5, 5, 1, 2, 2};  int n = arr.length;  int k = 3;   // Function Call  System.out.println("Maximum distinct elements = " +                       maxDistinctNum(arr, n, k));}} // This code is contributed by rutvik_56
<script> // Javascript implementation of the above approach   // function to find maximum distinct elements// after removing k elementsfunction maxDistinctNum(a, n, k){  var i;  var s = [];  // making multiset from given array        for(i=0;i<n;i++){            if(!s.includes(a[i])||k==0)            s.push(a[i]);            else            {                k--;            }        }           if(k!=0)            return s.size-k;        else{            var st = new Set();            s.forEach(element => {                st.add(element);            });                         return st.size;        }} // Driver Codevar arr = [5, 7, 5, 5, 1, 2, 2];var n = arr.length;var k = 3; // Function Calldocument.write( "Maximum distinct elements = "      +  maxDistinctNum(arr, n, k)); // This code is contributed by itsok.</script>
Maximum distinct elements = 4
Output:  
Maximum distinct elements = 4
Time Complexity: O(k*logd), where d is the number of distinct elements in the given array.
Another Approach: Follow the below steps, to solve this problem:
Find the Number of distinct Toys.
Sum of number of element except one element form every distinct Toys.
Check sum if greater than or equal K then Return all distinct element.
Otherwise decrement number of distinct element and to fill K.
Return Size of vector.
Below is the implementation of the above approach:
C++
// C++ code for the above approach#include <bits/stdc++.h>using namespace std;// function to return maximum number of distinct Toysint MaxNumber(int arr[], int N, int K){    // Count Number of distinct Number    unordered_map<int, int> mp;    for (int i = 0; i < N; i++) {        mp[arr[i]]++;    }    // push them into vector    vector<int> v1;    for (auto i : mp) {        v1.push_back(i.second);    }    // add number of element except one element from every    // distinct element    int temp = 0;    for (int i = 0; i < v1.size(); i++) {        temp += v1[i] - 1;    }    // check if it is greater then simply return size of    // vector otherwise decrement size of vector to fill k    if (K <= temp) {        return v1.size();    }    else {        K = K - temp;        int ans = v1.size();        while (K) {            ans--;            K--;        }        return ans;    }}// Driver Codeint main(){    // array    int arr[] = { 10, 10, 10, 50, 50 };    int K = 3;    // size of array    int N = sizeof(arr) / sizeof(arr[0]);    cout << MaxNumber(arr, N, K) << endl;    return 0;}
2
Time Complexity: O(N)
Space Complexity: O(N)
rachana soma
sonugiri
rutvik_56
deepanshujindal634
itsok
anikakapoor
sauarbhyadav
varshagumber28
sagar0719kumar
simmytarika5
cpp-priority-queue
Arrays
Hash
Heap
Arrays
Hash
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)