最简单的实现,以找到3个整数的最高乘积

时间:2016-07-20 02:10:29

标签: java arrays algorithm

我正在尝试计算数组中3个整数的最高可能乘积和。目前,我的算法通过使用几个if语句来解决这个问题。数组已排序,我已经计算了数组中的负整数数。

有没有更简单的方法来解决这个问题?

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 个答案:

答案 0 :(得分:1)

我的解决方案是检查最高值是否为正。如果是这样,我将最高值乘以数组中的第二高产品。否则,我会将最高值乘以最小乘积(以获得最高负数)。要查找最高或最小值,请使用Math.maxMath.min

.xcodeproj