Skip to content
Related Articles

Related Articles

Maximum distinct elements after removing k elements
  • Difficulty Level : Medium
  • Last Updated : 19 Oct, 2020

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. Build frequency map
  2. Add all no with freq=1 to result and push others to min-Heap.
  3. While K > 0, pick a top to reduce by 1 if freq==1 add to results.
  4. Otherwise –k and push top-1 to min-heap.

C++




// CPP implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
   
// function to find maximum distinct elements
// after removing k elements
int maxDistinctNum(int arr[], int n, int k)
{
    unordered_map<int, int> numToFreq;
       
    // Build frequency map
    for(int i = 0 ; i < n ; i++)
        ++numToFreq[ arr[i] ];
 
    int result=0;
   
    // Min-heap
    priority_queue<int,
               vector<int>, greater<int> > minHeap;
     
    // Add all number with freq=1 to
    // result and push others to minHeap
    for( auto p : numToFreq )
    {
        if( p.second == 1 ) // already distinct
            ++result;
        else
           minHeap.push( p.second );
    }
       
    // Perform k operations
    while( k && !minHeap.empty() )
    {
         
        // Pop the top() element
        auto t = minHeap.top();
        minHeap.pop();
           
          // Increment Result
        if( t == 1 )
        {
          ++result;
        }
           
        // Reduce t and k
        // Push it again
        else
        {
            --t;
            --k;
            minHeap.push( t );
        }
    }
   
    // Return result
    return result;
}
 
// Driver Code
int 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;
}
 
// This code is contributed by Sonu Giri


Java




// Java implementation of the
// above approach
import java.util.*;
class GFG{
     
// Function to find maximum
// distinct elements after
// removing k elements
static 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 code
public 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


Output: 
 

Maximum distinct elements = 4


Time Complexity: O(k*logd), where d is the number of distinct elements in the given array.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :