Search code examples
javascriptarraysalgorithm

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


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

and here is my code

function adjacentElementsProduct(inputArray) {
 var arr = inputArray;
  var x=0;
  var y=0;
  var p=0;
  for(var i=0;i<arr.length;i++){
    x=arr[i];
    y=arr[i+1];
    if(x*y>p){
     p=x*y;
    };
  };
 return p;
};

the problem is all the tests works fine but except the array with the negative product as it shown in the attached photo can anyone help .. and thanks in advance

enter image description here


Solution

  • You could start with a really large negative value, instead of zero.

    var p = -Infinity;