Longest subarray with absolute difference equal to some number in JavaScript



We are required to write a JavaScript function that takes in an array of Numbers as the first argument, let's say arr, and a number, let's say num, as the second argument. The function should find and return the length of the longest subarray (contiguous or non-contiguous) whose each pair has an absolute difference less than or equal to num.

For example, if the input array and the number are −

const arr = [7, 9, 8, 6, 6, 3]; const num = 1;

Then the output should be −

const output = 3,

because the desired subarray is [7, 6, 6]

Example

The code for this will be −

 Live Demo

const arr = [7, 9, 8, 6, 6, 3]; const maximumSubarray = (arr = [], num = 1) => {    if(!arr.length){       return 0;    };    const maximum = arr.reduce((acc, val) => Math.max(acc, val));    const buckets = new Array(maximum + 1);    buckets.fill(0);    const { length } = arr;    for(let i=0; i< length; i++){       buckets[arr[i]] += num;    };    let max = 0;    for(let j=1; j< maximum + 1; j++) {       let curr = buckets[j];       let prev = buckets[j - 1];       if(prev != 0 && prev + curr > max) {          max = prev + curr;       };    };    return max; }; console.log(maximumSubarray(arr));

Output

And the output in the console will be −

3
Updated on: 2021-02-24T16:20:56+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements