Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to .
Example
There are two subarrays meeting the criterion: and . The maximum length subarray has elements.
Function Description
Complete the pickingNumbers function in the editor below.
pickingNumbers has the following parameter(s):
- int a[n]: an array of integers
Returns
- int: the length of the longest subarray that meets the criterion
Input Format
The first line contains a single integer , the size of the array .
The second line contains  space-separated integers, each an .
Constraints
- The answer will be .
Sample Input 0
6
4 6 5 3 3 1
Sample Output 0
3
Picking Numbers HackerRank Solution in C
#include <stdio.h>
int main(void) {
    // your code goes here
    int n;scanf("%d",&n);
    int arr[101];
    int i,c=0;
    for(i=1;i<=100;i++)arr[i]=0;
    
    for(i=0;i<n;i++)
    {int x;
        scanf("%d",&x);
        arr[x]+=1;
    }
    for(i=1;i<100;i++)
    {
        int t=(arr[i]+arr[i+1]);
        if(t>c)
        c=t;
    }
    printf("%d",c);
    return 0;
}
Picking Numbers HackerRank Solution in C++
#include <bits/stdc++.h>
using namespace std;
int N;
int A[1000];
int main()
{
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        int a;
        scanf("%d", &a);
        A[a]++;
    }
    int ans=0;
    for(int i=1; i<1000; i++)
        ans=max(ans, A[i-1]+A[i]);
    printf("%d\n", ans);
    return 0;
}
Picking Numbers HackerRank Solution in Java
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[100];
        for(int a_i=0; a_i < n; a_i++){
            a[in.nextInt()]++;
        }
        int max = 0;
        for (int i = 0; i < 99; i++) {
            max = Math.max(max, a[i]+a[i+1]);
        }
        System.out.println(max);
    }
}
Picking Numbers HackerRank Solution in Python
#!/bin/python
import sys
n = int(raw_input().strip())
a = map(int,raw_input().strip().split(' '))
a.sort()
ans = 0
for i in xrange(n):
    for j in xrange(n):
        if abs(a[j] - a[i]) <= 1:
            ans = max(ans, j - i + 1)
print ans
Attempt Picking Numbers HackerRank Challenge
Link – https://www.hackerrank.com/challenges/picking-numbers
Next HackerRank Challenge Solution
Link – https://exploringbits.com/climbing-the-leaderboard-hackerrank-solution/
Aayush Kumar Gupta is the founder and creator of ExploringBits, a website dedicated to providing useful content for people passionate about Engineering and Technology. Aayush has completed his Bachelor of Technology (Computer Science & Engineering) from 2018-2022. From July 2022, Aayush has been working as a full-time Devops Engineer.
