# Count of subsequences having maximum distinct elements in C++

C++Server Side ProgrammingProgramming

We are given an array arr[] containing integers only. The goal is to find the number of subsequences of arr[] such that they have maximum number distinct elements. If the array is [ 4,1,2,3,4 ] then two subsequences will be [ 4,1,2,3 ] and [ 1,2,3,4 ].

Let us understand with examples

Input − arr[]= { 1,3,5,4,2,3,1 }

Output − Count of subsequences having maximum distinct elements are − 4

Explanation − The maximum distinct elements are 1,2,3,4 and 5. Count is 5. Subsequences will be −

[ 1,3,5,4,2 ], [ 3,5,4,2,1], [ 5,4,2,3,1 ], [ 1,5,4,2,3 ].

Input − arr[]= { 5,4,2,1,3 }

Output − Count of subsequences having maximum distinct elements are − 1

Explanation − All elements are distinct. Number of subsequences will be 1.

## Approach used in the below program is as follows

In this approach we will find subsequences based on the fact that if all elements are distinct then the number of subsequences is 1 that is the array itself. In case there are repeated elements then each repeated element will be part of a new subsequence. So we will create a unorderdered_map of frequencies of distinct elements. Then for each frequency multiply that frequency to count. At the end count has a total number of frequencies.

• Take an integer array arr[] as input.

• Function Max_distinct_subseq(int arr[], int size) takes the array and its size and returns the count of subsequences with maximum distinct elements.

• Take the initial count as 1 as if all elements are distinct then the array itself is subsequence with maximum distinct elements.

• Create unordered_map<int, int> hash; to store frequencies of all distinct elements.

• Traverse the array using for loop and update frequencies for each element arr[i] using hash[arr[i]]]++.

• Now traverse the hash using a for loop. For each frequency it->second( it=iterator) multiply to previous count. As x elements of the same time will be part of x different subsequences.

• At the end count has a total number of frequencies.

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int Max_distinct_subseq(int arr[], int size){
int count = 1;
unordered_map<int, int> hash;
for (int i = 0; i < size; i++){
hash[arr[i]]++;
}
for (auto it = hash.begin(); it != hash.end(); it++){
count = count * (it->second);
}
return count;
}
int main(){
int arr[] = { 3, 7, 3, 3, 1, 5, 6, 9 };
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of subsequences having maximum distinct elements are: "<<Max_distinct_subseq(arr, size);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of subsequences having maximum distinct elements are: 3
Published on 02-Dec-2020 16:32:43