Skip to content
Advertisement

Javascript: adjacent Elements Product algorithm

I’m trying to solve a basic javascript algorithm and i’m kinda stuck, here is the question:

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

Example

For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.

7 and 3 produce the largest product.

Here is my code, i can’t find the problem but in the tests it says that it returns null:

    function adjacentElementsProduct(inputArray) {
    var cb;
    for(var i=0;i<inputArray.length;i++){
      if(inputArray[i] !== inputArray[inputArray.length-1]){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
      }
    }
  return cb;
  }

What is my problem and what i need to change?

Advertisement

Answer

The problem with your code is you never initialized cb. So the comparison with cb is always invalid. Here is the correct version of your code –

function adjacentElementsProduct(inputArray) {
    var cb = Number.NEGATIVE_INFINITY;
    for(var i=0;i<inputArray.length-1;i++){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
    }
  return cb;
}

console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 7]))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement