Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1.
Examples:
Input array:
6, 4, 6, 8, 5, 9, 9, 9, 10, 3
Output:
4
Example with explanation:
The input array is: 6, 4, 6, 8, 5, 9, 9, 9, 10, 3
No we can pick up different sets for which the absolute difference between any two numbers in the set is 1.
Possible sets are:
{6, 6, 5}
{4, 5}
{8, 9, 9, 9}
{9, 9, 9, 10}
{4, 3}
Thus maximum no of picked up elements is: 4
Algorithm:
This problem can be implemented with help of map data structure. We have used STL for map implementation. (For details regarding STL map, C++ STL Map)
FUNCTION pickingNumbers(input array) 1. Declare map<int,int>m to store key with their frequencies; 2. Build the map. For i=0:length of array m[array[i]]++; 3. Declare max as INT_MIN; 4. Declare map<int,int>::iteratorit; 5. For(it=m.begin();it!=m.end();it++) IF (it+1==m.end()) //last case IF(it->second>max) max=it->second; END IF ELSE IF(it->first+1==(it+1)->first){ //absolute difference is 1 IF((it->second +(it+1)->second)>max) max=it->second +(it+1)->second; END IF ELSE IF(it->second>max) //absolute difference 0 case max=it->second; END IF END IF-ELSE END FOR 6. return max; END FUNCTIONAlgorithm is pretty simple.
We first extract the unique numbers and store their frequencies. Then we simply check for two unique number's additive frequency or any one unique number's frequency itself and return the greater one.
Let's solve the above example.
The input array is: 6, 4, 6, 8, 5, 9, 9, 9, 10, 3 Map m: Key Frequency 3 1 4 1 5 1 6 2 8 1 9 3 10 1 So if we do all the iterations then each iteration, maxgets to be updated(or not, keeps last value) From this map, we can see max is 4 1+3 //one 8 and three 9 3+1 //three 9 and one 10 Now lets think that we append six 12 to the array Thus input is now: 6, 4, 6, 8, 5, 9, 9, 9, 10, 3, 12, 12, 12, 12, 12, 12 Map m: Key Frequency 3 1 4 1 5 1 6 2 8 1 9 3 10 1 12 6 Now the max will be 6 //absolute difference 0 case Since the subset will be {12, 12, 12, 12, 12, 12}C++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer