Solve the problem

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

function adjecmentElementProduct(arr){
    let l = 0;
    for(var i = 0; i < arr.length; i++){
        if(arr[i] * arr[i + 1] > l){
            l = arr[i] * arr[i + 1];
        }        
    }
    return l;
}

adjecmentElementProduct([-23,4,-3,8, -12]);

the answer should be -12
but it gives 0 why?
solve this problem

Because 0 is greater than -12 and you initialize your l variable as 0. Initialize l as adjecmentElementProduct[0] * adjecmentElementProduct[1], so your code becomes:

function adjecmentElementProduct(arr){
    let l = adjecmentElementProduct[0] * adjecmentElementProduct[1];//of course, you need to make sure the array has a length of at least 2
    for(var i = 0; i < arr.length; i++){
        if(arr[i] * arr[i + 1] > l){
            l = arr[i] * arr[i + 1];
        }        
    }
    return l;
}

. I assume whoever made this exercise wanted to teach those who initialize the result variable as 0 a lesson that when you deal with arrays of negative values you risk running into trouble.

1 Like

thank you so much sir.