# Find maximum number of elements such that their absolute difference is less than or equal to 1 in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements. We have to find the maximum number of elements to select from the array, such that the absolute difference between any two of the chosen elements is less than or equal to 1. So if the array is like [2, 2, 3, 4, 5], then the element will be 3, so the sequence with maximum count is 2, 2, 3.

The absolute difference of 0 and 1 means, that the number can be of type x and x + 1. So the idea is to store the frequencies of array elements. So if we find the maximum sum of any two consecutive elements, it will be the solution.

## Example

Live Demo

#include <iostream>
#include <map>
using namespace std;
int maxElem(int arr[], int n) {
map<int,int> occurrence;
for(int i=0;i<n;++i){
if(occurrence[arr[i]])
occurrence[arr[i]] += 1;
else
occurrence[arr[i]] = 1;
}
int ans = 0, key;
map<int,int>:: iterator it=occurrence.begin();
while(it!=occurrence.end()) {
key = it->first;
++it;
if(occurrence[key+1]!=0)
ans=max(ans,occurrence[key]+occurrence[key+1]);
}
return ans;
}
int main(){
int arr[] = {2, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Result is: " << maxElem(arr, n);
}

## Output

Result is: 3
Published on 18-Dec-2019 10:09:20