Open In App

Maximize count of distinct elements in a subsequence of size K in given array

Last Updated : 14 Dec, 2021
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers.

Example:

Input: arr[]={1, 1, 2, 2}, K=3
Output: 2
Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are 2 which is the maximum possible. Other possible subsequence is {1, 2, 2}.

Input: arr[]={1, 2, 3, 4}, K=3
Output: 3

Approach: The given problem can be solved using a greedy approach using the observation that the required answer is the minimum of the count of the unique elements in the given array or K. Now, to solve this problem, follow the below steps:

  1. Create a set S, which stores the distinct integers present in the array arr[].
  2. Traverse the array arr[] and insert each number in the set S.
  3. Return the minimum of K and the size of S which is the required answer.

Below is the implementation of the above approach:

C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find count of maximum
// distinct elements in a subsequence
// of size K of the given array arr[]
int maxUnique(vector<int>& arr, int K)
{
    // Set data structure to
    // store the unique elements
    unordered_set<int> S;

    // Loop to traverse the given array
    for (auto x : arr) {

        // Insert into the set
        S.insert(x);
    }

    // Returning the minimum out of the two
    return min(K, (int)S.size());
}

// Driver Code
int main()
{
    vector<int> arr = { 1, 1, 2, 2 };
    int K = 3;
    cout << maxUnique(arr, K);
}
Java Python3 C# JavaScript

 
 


Output
2


 

Time Complexity: O(N)
Auxiliary Space: O(N)


 


Next Article

Similar Reads