The problem is that it doesn't work with negative numbers as in the following example, can someone help me to find out what my mistake is. I've tried with -infinite but it doesn't work for me or maybe I use it wrong. THANK YOU!!!
function solution(inputArray) {
var mult1 = 0;
var mult2 = 0;
var max = 0;
var ult = 0;
for(i=0;i<inputArray.length;i++){
mult2 = mult1;
mult1 = inputArray[i] * inputArray[i+1];
if(mult1 > mult2){
max = mult1;
if(max > ult){
ult = max;
}else{
ult = ult;
};
}else{
max = mult2;
if(max > ult){
ult = max;
}else{
ult = ult;
};
};
};
console.log(ult);
};
solution([-23, 4, -3, 8, -12]);
You are initializing the value of
max
zero, therefore, in an array where all the products are negative, your algorithm will not work. It's best to initialize your variable to the smallest possible value, in this case,Number.NEGATIVE_INFINITY;
.On the other hand you are making a lot of comparisons for no reason. You should only replace the maximum value if the current product is greater than the value you have saved. I attach an example:
Alternatively you can store all the products in an array and finally return the maximum: