Longest subarray with unit difference in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument

Our function should find and return the length of such a subarray where the difference between its maximum value and its minimum value is exactly 1.

For example, if the input to the function is −

const arr = [2, 4, 3, 3, 6, 3, 4, 8];

Then the output should be −

const output = 5;

Output Explanation

Because the desired subarray is [4, 3, 3, 3, 4]

Example

Following is the code −

const arr = [2, 4, 3, 3, 6, 3, 4, 8];
const longestSequence = (arr = []) => {
   const map = arr.reduce((acc, num) => {
      acc[num] = (acc[num] || 0) + 1
      return acc
   }, {})

   return Object.keys(map).reduce((max, key) => {
      const nextKey = parseInt(key, 10) + 1
   if (map[nextKey] >= 0) {
      return Math.max(
         max,
         map[key] + map[nextKey],
      )
   }
   return max
   }, 0);
};
console.log(longestSequence(arr));

Output

Following is the console output −

5
raja
Published on 21-Apr-2021 12:13:48
Advertisements