703026. Maximum distinct elements after removing K elements

Medium

Here is the detailed markdown blog post for the problem:

Maximum distinct elements after removing K elements

Summary

Given an array of integers, find the maximum number of distinct elements that can be obtained by removing at most K elements. The problem requires us to use a combination of hash and heap data structures to solve it efficiently.

Detailed Explanation


To solve this problem, we first initialize a frequency map using a hash (unordered_map in C++ or dict in Python) to store the frequency of each element in the array. Then, we create a priority queue (max heap) to keep track of the most frequent elements.

Here's the step-by-step breakdown:

  1. Initialize an empty hash and a priority queue.
  2. Iterate through the given array and update the frequency map for each element.
  3. For each element in the frequency map, add its frequency as a negative value to the priority queue (since we want the most frequent elements first).
  4. Remove K elements from the top of the priority queue.
  5. The remaining elements in the priority queue represent the maximum number of distinct elements that can be obtained by removing at most K elements.

Time Complexity Analysis

The time complexity of this solution is O(n log n), where n is the size of the input array. This is because we are using a priority queue, which has a logarithmic time complexity for operations like insertion and deletion.

Space Complexity Analysis

The space complexity of this solution is O(n), where n is the size of the input array. This is because we need to store the frequency map and the priority queue, both of which have a linear size proportional to the input size.

Optimized Solutions


Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static int maximumDistinctElements(int[] arr, int K) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());

        for (int num : arr) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
            pq.offer(new AbstractMap.SimpleEntry<>(entry.getKey(), -entry.getValue()));
        }

        int distinctElements = 0;
        while (!pq.isEmpty() && K-- > 0) {
            pq.poll();
        }

        while (!pq.isEmpty()) {
            distinctElements++;
            pq.poll();
        }

        return distinctElements;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.