- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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); }

Result is: 3

- Related Questions & Answers
- Find three integers less than or equal to N such that their LCM is maximum - C++
- Find three integers less than or equal to N such that their LCM is maximum in C++
- Find unique pairs such that each element is less than or equal to N in C++
- C++ program to find unique pairs such that each element is less than or equal to N
- Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k in C++
- Find maximum sum array of length less than or equal to m in C++
- Find maximum product of digits among numbers less than or equal to N in C++
- Number of elements less than or equal to a given number in a given subarray in C++
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++
- Find Largest Special Prime which is less than or equal to a given number in C++
- Find Multiples of 2 or 3 or 5 less than or equal to N in C++
- Find all factorial numbers less than or equal to n in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Maximum sum subarray having sum less than or equal to given sums in C++
- Count elements such that there are exactly X elements with values greater than or equal to X in C++

Advertisements