Maximize count of distinct elements in a subsequence of size K in given array
Last Updated :
14 Dec, 2021
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:
- Create a set S, which stores the distinct integers present in the array arr[].
- Traverse the array arr[] and insert each number in the set S.
- Return the minimum of K and the size of S which is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxUnique(vector< int >& arr, int K)
{
unordered_set< int > S;
for ( auto x : arr) {
S.insert(x);
}
return min(K, ( int )S.size());
}
int main()
{
vector< int > arr = { 1, 1, 2, 2 };
int K = 3;
cout << maxUnique(arr, K);
}
|
Java
import java.util.*;
class GFG{
static int maxUnique( int []arr, int K)
{
HashSet<Integer> S = new HashSet<Integer>();
for ( int x : arr) {
S.add(x);
}
return Math.min(K, ( int )S.size());
}
public static void main(String[] args)
{
int [] arr = { 1 , 1 , 2 , 2 };
int K = 3 ;
System.out.print(maxUnique(arr, K));
}
}
|
Python3
def maxUnique(arr, K):
S = set ()
for x in arr:
S.add(x)
return min (K, len (S))
arr = [ 1 , 1 , 2 , 2 ]
K = 3
print (maxUnique(arr, K))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
static int maxUnique( int []arr, int K)
{
HashSet< int > S = new HashSet< int >();
foreach ( int x in arr) {
S.Add(x);
}
return Math.Min(K, ( int )S.Count);
}
public static void Main()
{
int []arr = { 1, 1, 2, 2 };
int K = 3;
Console.Write(maxUnique(arr, K));
}
}
|
Javascript
<script>
function maxUnique(arr, K)
{
let S = new Set();
for (let x of arr) {
S.add(x);
}
return Math.min(K, S.size);
}
let arr = [1, 1, 2, 2];
let K = 3;
document.write(maxUnique(arr, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...