gpt4 book ai didi

java - 找到 3 个整数的最高乘积的最简单实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:17:49 27 4
gpt4 key购买 nike

我正在尝试计算数组中 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;
}
}

最佳答案

我的解决方案是检查最大值是否为正。如果是这样,我将最高值乘以数组中第二高的乘积。否则我会将最大值乘以最小的乘积(以获得最大的负数)。为了找到最高或最小值,我使用 Math.maxMath.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]);

关于java - 找到 3 个整数的最高乘积的最简单实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38471210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com