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

Given an array of integers, find the pair of adjacent elements that has the largest product and return that product JavaScript


We are required to write a JavaScript function that takes in an array of Numbers (positive and negative numbers).

The function should return the highest product of two adjacent elements of the array.

For example −

If the input array is −

const arr = [-23, 4, -3, 8, -12];

Then the output should be −

const output = -12;

and the two elements are 4 and -3

Example

const arr = [-23, 4, -3, 8, -12];
const adjacentProduct = (arr = []) => {
   let first = 0;
   let second = 0;
   let res = Number.MIN_SAFE_INTEGER;
   for (let i = 0;
   i < arr.length; i++) {
      first = arr[i];
      second = arr[i + 1];
      if (first * second > res) {
         res = first * second;
      };
   };
   return res;
};
console.log(adjacentProduct(arr));

Output

This will produce the following output −

-12