In this Picking Numbers HackerRank solution, 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 .
Picking Numbers HackerRank Solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function pickingNumbers(a) {
a.sort();
let base = a[0];
let lengths = [];
let length = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] === base || a[i] === base + 1){
length ++;
if(i === a.length-1){
lengths.push(length);
}
}else{
lengths.push(length);
length = 1;
base = a[i];
}
}
lengths.sort((a,b)=> b-a);
return lengths[0];
}
Problem Solution in Python
def pickingNumbers(a):
a.sort()
sub_arr = {}
for e in a:
if e in sub_arr:
sub_arr[e] += 1
elif e - 1 in sub_arr:
sub_arr[e-1] += 1
else:
sub_arr[e] = 1
return max(sub_arr.values())
Problem Solution in C#
public static int pickingNumbers(List<int> a)
{
int max = 0;
int [] c = new int[100];
for(int i = 0; i < a.Count; i++)
{
c[a[i]]++;
}
for(int i =1 ; i < 99; i++)
{
max = Math.Max(max, c[i] + c[i+1]);
}
return max;
}
Problem Solution in Java
public static int pickingNumbers(List<Integer> a) {
Integer[] arr = new Integer[100];
Arrays.fill(arr, 0);
for(Integer v : a) {
Integer idx = v - 1;
arr[idx]++;
}
Integer maximum = Integer.MIN_VALUE;
for(int i = 1; i < arr.length; i++) {
int sum = arr[i - 1] + arr[i];
if(sum > maximum) {
maximum = sum;
}
}
return maximum;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems