Home > Back-end >  find the pair of adjacent elements that has the largest product (incorrect message)
find the pair of adjacent elements that has the largest product (incorrect message)

Time:10-02

i keep getting incorrect message please explain me what is wrong?

here is the challenge question: Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. Example

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

7 and 3 produce the largest product.

here is my code answer:

function adjacentElementsProduct(inputArray) {
for(let i=0;i<inputArray.length;i  ){
    let prod =Math.max(inputArray[i]*inputArray[i 1]);
   

}
 return prod;
}

CodePudding user response:

When the index reaches to the length of inputArray, the inputArray[i 1] will throw an OutOfIndex error, since the indexes' range are from 0 to inputArray.length - 1, and here the last i will have the value of inputArray.length - 1 then the value of i 1 will be inputArray.length and it's not correct.
You should change your code like this, to get the correct output:

function adjacentElementsProduct(inputArray) {
  for (let i = 0; i < inputArray.length - 1; i  ) {
    // changed the limit
    let prod = Math.max(inputArray[i] * inputArray[i   1]);
  }
  return prod;
}

CodePudding user response:

1) You have to get the max of two numbers as

sum = Math.max(sum, inputArray[i] * (inputArray[i   1] ?? 1));

2) You also have to handle the last case where i 1 will be undefined then you have multiply by 1. You can use null coalescing operator

(inputArray[i   1] ?? 1)

function adjacentElementsProduct(inputArray) {
  let sum = 0;
  for (let i = 0; i < inputArray.length; i  ) {
    sum = Math.max(sum, inputArray[i] * (inputArray[i   1] ?? 1));
  }
  return sum;
}

const inputArray = [3, 6, -2, -5, 7, 3];
console.log(adjacentElementsProduct(inputArray));

  • Related