In this post, we will solve the Picking Numbers HackerRank Solution. This problem (Picking Numbers) is a part of the HackerRank Problem Solving series.
Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to 1.
Example
a= [1, 1, 2, 2, 4, 4, 5, 5, 5]
Original Problem Link: https://www.hackerrank.com/challenges/three-month-preparation-kit-picking-numbers/problem
Picking Numbers Hacker Rank Solution
Problem solution in JavaScript programming:
function pickingNumbers(a) { let map = {}; let max = 0; for (let item of a){ let first = item; let second = item -1; let temp; map[first] = map[first] ? map[first] + 1 :1; map[second] = map[second ] ? map[second] + 1 :1; temp= Math.max(map[first],map[second]); max = Math.max(max,temp) } return max }
Problem solution in Python programming:
def pickingNumbers(a): count = [0] * (int(max(a)) + 1) for i in a: count[i] += 1 maxVal = 0 for i in range(1, len(count)-1): maxVal = (max(count[i] + count[i-1], count[i] + count[i+1], maxVal)) return maxVal
Problem solution in Java programming:
public static int pickingNumbers(List<Integer> a) { // Write your code here int maxSubArrSize = 0; Collections.sort(a); for (int i=0; i<a.size()-1; i++) { int subArrSize = 1; for (int j=i+1;j<a.size(); j++) { if(Math.abs(a.get(i)-a.get(j)) <= 1) { subArrSize++; } else { break; } } if (subArrSize > maxSubArrSize) { maxSubArrSize = subArrSize; } } return maxSubArrSize; }
Leave a Reply