Maximum product of any two adjacent elements in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers.

Our function should find the maximum product obtained from multiplying 2 adjacent numbers in the array.

Example

Following is the code −

 Live Demo

const arr = [9, 5, 10, 2, 24, -1, -48];
function adjacentElementsProduct(array) {
   let maxProduct = array[0] * array[1];
   for (let i = 1; i < array.length; i++) {
      product = array[i] * array[i + 1];
      if (product > maxProduct)
         maxProduct = product;
   }
   return maxProduct;
};
console.log(adjacentElementsProduct(arr));

Output

50

Updated on: 17-Apr-2021

531 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements