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

Given an array of n elements, 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.
Examples:Â
Input : arr[] = {1, 2, 3}
Output : 2
We can either take 1, 2 or 2, 3.
Both will have the count 2 so maximum count is 2
Input : arr[] = {2, 2, 3, 4, 5}
Output : 3
The sequence with maximum count is 2, 2, 3.
The absolute difference of 0 or 1 means that the numbers chosen can be of type x and x+1. Therefore, the idea is to store frequencies of array elements. So, the task now reduces to find the maximum sum of any two consecutive elements.
Below is the implementation of the above approach:Â Â
C++
// CPP program to find maximum number of// elements such that their absolute// difference is less than or equal to 1#include <bits/stdc++.h>using namespace std;Â
// function to return maximum number of elementsint maxCount(int n,int a[]){    // Counting frequencies of elements    map<int,int> freq;Â
    for(int i=0;i<n;++i){        if(freq[a[i]])            freq[a[i]] += 1;        else            freq[a[i]] = 1;    }Â
    // Finding max sum of adjacent indices    int ans = 0, key;Â
    map<int,int>:: iterator it=freq.begin();Â
    while(it!=freq.end())    {        key = it->first;Â
        // increment the iterator        ++it;Â
        if(freq[key+1]!=0)            ans=max(ans,freq[key]+freq[key+1]);Â
    }Â
    return ans;}Â
// Driver Codeint main(){Â Â Â Â int n = 5;Â Â Â Â int arr[] = {2, 2, 3, 4, 5};Â
    // function call to print required answer    cout<<maxCount(n,arr);Â
    return 0;}Â
Â
// This code is contributed by Sanjit_Prasad |
Java
// Java program to find the maximum number // of elements such that their absolute // difference is less than or equal to 1 import java.util.HashMap;import java.util.Map;import java.lang.Math;Â
class GfG{Â
    // function to return the maximum number of elements     static int maxCount(int n,int a[])     {         // Counting frequencies of elements         HashMap<Integer, Integer> freq = new HashMap<>();              for(int i = 0; i < n; ++i)        {             if(freq.containsKey(a[i]))                 freq.put(a[i], freq.get(a[i]) + 1);             else                freq.put(a[i], 1);         }              // Finding max sum of adjacent indices         int ans = 0;              for (Integer key : freq.keySet())         {             if(freq.containsKey(key+1))                 ans = Math.max(ans, freq.get(key) + freq.get(key+1));         }              return ans;     } Â
    // Driver code    public static void main(String []args)    {                 int n = 5;         int arr[] = {2, 2, 3, 4, 5};              // function call to print required answer         System.out.println(maxCount(n,arr));    }}Â
// This code is contributed by Rituraj Jain |
Python3
# Python program to find maximum number of # elements such that their absolute# difference is less than or equal to 1Â
def maxCount(a):Â
    # Counting frequencies of elements    freq = {}    for i in range(n):        if (a[i] in freq):             freq[a[i]] += 1        else:             freq[a[i]] = 1                  # Finding max sum of adjacent indices       ans = 0    for key, value in freq.items():         if (key+1 in freq) :               ans = max(ans, freq[key] + freq[key + 1])          return ans     # Driver Code n = 5arr = [2, 2, 3, 4, 5]Â
print(maxCount(arr)) |
C#
// C# program to find the maximum number // of elements such that their absolute // difference is less than or equal to 1 using System;using System.Collections.Generic;Â
class GfG { Â
    // function to return the maximum number of elements     static int maxCount(int n,int []a)     {         // Counting frequencies of elements         Dictionary<int,int> mp = new Dictionary<int,int>();                 // Increase the frequency of elements        for (int i = 0 ; i < n; i++)        {            if(mp.ContainsKey(a[i]))            {                var val = mp[a[i]];                mp.Remove(a[i]);                mp.Add(a[i], val + 1);             }            else            {                mp.Add(a[i], 1);            }        }              // Finding max sum of adjacent indices         int ans = 0;              foreach(KeyValuePair<int, int> e in mp)        {             if(mp.ContainsKey(e.Key+1))                 ans = Math.Max(ans, mp[e.Key] + mp[e.Key+1]);         }              return ans;     } Â
    // Driver code     public static void Main(String []args)     {                  int n = 5;         int []arr = {2, 2, 3, 4, 5};              // function call to print required answer         Console.WriteLine(maxCount(n,arr));     } } Â
/* This code is contributed by PrinciRaj1992 */ |
Javascript
<script>Â
// JavaScript program to find maximum number of// elements such that their absolute// difference is less than or equal to 1Â
// function to return maximum number of elementsfunction maxCount(n,a){    // Counting frequencies of elements    var freq = new Map();Â
    for(var i=0;i<n;++i){        if(freq.has(a[i]))            freq.set(a[i], freq.get(a[i])+1)        else            freq.set(a[i], 1)    }Â
    // Finding max sum of adjacent indices    var ans = 0, key;Â
    freq.forEach((value, key) => {                if(freq.has(key+1))            ans=Math.max(ans,freq.get(key)+freq.get(key+1));    });Â
    return ans;}Â
// Driver CodeÂ
var n = 5;var arr =Â [2, 2, 3, 4, 5];Â
// function call to print required answerdocument.write( maxCount(n,arr));Â
</script> |
Output
3
Complexity Analysis:
- Time Complexity: O(n * log(n))
- Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



