Picking Numbers - HakerRank Solution - Javascript
Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to
Example
_a = [1,1,2,2,4,4,5,5,5]_
There are two subarrays meeting the criterion: [1,1,2,2]
and [4,4,5,5,5]
. The maximum length subarray has 5 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 n, the size of the array a. The second line contains n space-separated integers, each an a[i].
Solution
function pickingNumbers(a) {
// Create an array to store frequency of each element in the input array
let frequency = new Array(100).fill(0);
// Count frequency of each element
for (let i = 0; i < a.length; i++) {
frequency[a[i]]++;
}
// Initialize a variable to store the maximum length of subarray found
let maxLength = 0;
// Traverse through frequency array to find the longest subarray
for (let i = 1; i < frequency.length; i++) {
// The length of a valid subarray is the sum of the frequency of
// the current element and the previous element
maxLength = Math.max(maxLength, frequency[i] + frequency[i - 1]);
}
return maxLength;
}
Subscribe to my newsletter
Read articles from Ibukun demehin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ibukun demehin
Ibukun demehin
I am a skilled and passionate React frontend developer with a strong foundation in building captivating user interfaces and seamless web experiences. With a meticulous eye for detail and a deep understanding of modern web development principles, I thrive in creating elegant, responsive, and intuitive designs that enhance user engagement. Throughout my career, I have honed my expertise in React, utilizing its powerful components and state management to craft dynamic and interactive user interfaces. From designing pixel-perfect layouts to implementing smooth transitions and animations, I possess a knack for transforming complex concepts into visually appealing and user-friendly solutions. In addition to React, I am well-versed in HTML, CSS, and JavaScript, allowing me to build cohesive and well-structured front-end architectures. I am also experienced in leveraging various libraries and frameworks, such as Redux, TypeScript, and Material-UI, to optimize development processes and deliver high-quality code.