Computer >> Computer tutorials >  >> Programming >> Javascript

Maximum decreasing adjacent elements in JavaScript


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