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;
}
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.max_res
) to save the prevoius maximum result and compare it to new results.prod
variable before the for loop
, because variables which are first defined in the loop
they won't be accessible after the loop
ends.i
that makes the maximum value, since the question wanted the index ,too.You should change your code like this, to get the correct output:
function adjacentElementsProduct(inputArray) {
let max_res = Number.NEGATIVE_INFINITY;
let res_index = -1;
let prod = 0;
for (let i = 0; i < inputArray.length - 1; i++) {
prod = Math.max(inputArray[i] * inputArray[i + 1]);
if (prod > max_res){
max_res = prod;
let res_index = i;
}
}
return prod;
}
let inputArray = [3, 6, -2, -5, 7, 3]
let prod = adjacentElementsProduct(inputArray)
console.log(prod);
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));
Number.MIN_SAFE_INTEGER
will allow the smallest integer because this needs to find the largest sum which may include negative integers.
function solution(inputArray) {
let largestProduct = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < inputArray.length; i++) {
if(inputArray[i] * inputArray[i + 1] > largestProduct) {
largestProduct = inputArray[i] * inputArray[i + 1];
}
}
return largestProduct;
}