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

JavaScript: Adjacent Elements Product Algorithm


We are given an array of integers. We are required to find the pair of adjacent elements that have the largest product and return that product.

For example −

If the input array is −

const arr = [3, 6, -2, -5, 7, 3];

Then the output should be 21 because [7, 3] is the pair with the greatest sum.

Example

Following is the code −

const arr = [3, 6, -2, -5, 7, 3];
const adjacentElementsProduct = (arr = []) => {
   let prod, ind;
   for (ind = 1; ind < arr.length; ind++) {
      if (ind === 1 || arr[ind - 1] * arr[ind] > prod) {
         prod = arr[ind - 1] * arr[ind];
      };
   };
   return prod;
};
console.log(adjacentElementsProduct(arr));

Output

Following is the output on console −

21