Maximum decreasing adjacent elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given an array of integers, and we are required to find the maximal absolute difference between any two of its adjacent elements.

For example: If the input array is −

const arr = [2, 4, 1, 0];

Then the output should be −

const output = 3;

because, the maximum absolute difference is in the elements 4 and 1.

Example

The code for this will be −

const arr = [2, 4, 1, 0];
const maximumDecreasing = (arr = []) => {
   const res = arr.slice(1).reduce((acc, val, ind) => {
      return Math.max(Math.abs(arr[ind] − val), acc);
   }, 0);
   return res;
};
console.log(maximumDecreasing(arr));

Output

And the output in the console will be −

3
raja
Published on 23-Nov-2020 07:53:31
Advertisements