0

I am trying to calculate the highest possible product sum of 3 integers in an array. At the moment my algorithm solves this by using several if statements. The array is sorted and I have already calculated the number of negative integers in the array.

Is there an easier way to solve this?

if (nbr_of_negative < 2) {
        // If the number of negatives are lower than 2, the 3 highest positive numbers generate the highest product.
        return array_of_ints[array_of_ints.length-1] * array_of_ints[array_of_ints.length-2] * array_of_ints[array_of_ints.length-3];
    } else {
        // If the number of negatives are 2 or higher, you take the highest number together with the
        // product of the two lowest or the product of the second and third highest number.
        int product_of_two_negative = (array_of_ints[0] * -1) * (array_of_ints[1] * -1);
        int product_of_two_positive = array_of_ints[array_of_ints.length-2] * array_of_ints[array_of_ints.length-3];
        int highest_value = array_of_ints[array_of_ints.length-1];

        if (product_of_two_negative > product_of_two_positive) {
            return product_of_two_negative * highest_value;
        } else {
            return product_of_two_positive * highest_value;
        }
    }

1 Answers1

1

My solution is to check if the highest value is positive. If so I multiply the highest value with the second highest product in the array. Otherwise I will multiply the highest value with the smallest product (to get the highest negative number). To find the highest or smallest values I use Math.max and Math.min.

    Arrays.sort(helpArray);
    int product = 0;
    if(helpArray[helpArray.length-1]>0) //array is sorted in ascending order
         product = helpArray[helpArray.length-1] * Math.max(helpArray[0]*helpArray[1], helpArray[helpArray.length-2] * helpArray[helpArray.length-3]);
    else
        product = helpArray[helpArray.length-1] * Math.min(helpArray[0]*helpArray[1], helpArray[helpArray.length-2] * helpArray[helpArray.length-3]);
fridayswag
  • 359
  • 6
  • 12