Search code examples
javaarrayscomparemultiplicationnegative-number

Multiplying adjacent elements and compare which has a higher value


I am trying to compare which has a greater quotient when multiplying adjacent elements:

public static void main(String args[]) {
    int[] inputArray = {-5, 8, -9, 1, -5, 4};
    int x = 0;
    long maxsofar = 0;
    while (x < inputArray.length - 1) {
        int currentmax = inputArray[x] * inputArray[x + 1];
        maxsofar = (maxsofar > currentmax) ? maxsofar : currentmax;
        }
        x++;
    }
    System.out.println(maxsofar);
}

So far my code works, but when I try to use negative integers on my array, it just outputs 0.


Solution

  • That's probably because 0 is > than negative numbers. All your adjacent elements when multiplied create negative numbers->

    -5*8=-40

    8*-9=-72

    etc.

    So 0 is the maximum one.

    You can use Math.abs() for example to use the absolute value. Or you can set maxsofar to the Long.MIN_VALUE to get the largest number even if negative. The way you have done it you get the largest number > 0.

    And also this way your program works for exactly that array (having 5 elemtents). A nicer way would be:

    for (int i = 0; i < inputArray.length - 2; i++) {
                int currentmax = inputArray[i] * inputArray[i + 1];
                if (maxsofar < currentmax) {                
                    maxsofar = currentmax;
                } //No need to handle the case where you say A=A :)
            }
    

    Or even better you can do Math.max(maxsofar,currentmax);