int arr[] = {10, 10, 1, 3};
假设:假设每个整数都是正的。假设数组包含至少 3 个整数
从上面数组中的三个整数中找出你能得到的最高乘积。我们应该返回 300(通过取 10 * 10 * 3 得到)。
我想用蛮力法解决这个问题。基本上,我想将每个整数乘以其他整数,然后将该乘积乘以其他整数。任何人都可以告诉我如何使用嵌套的 3 个循环来完成这件事因为我想在尝试优化方法之前先了解如何使用蛮力来完成。
谢谢。
最佳答案
使用三个 for 循环:
public static Integer highestProduct(int array[])
{
if((array==null)||(array.length<3))
{
return null;
}
else
{
int max_product = Integer.MIN_VALUE;
for(int i=0;i<array.length;i++)
{
for(int j=i+1;j<array.length;j++)
{
for(int k=j+1;k<array.length;k++)
{
int product = array[i]*array[j]*array[k];
if(product>=max_product)
{
max_product = product;
}
}
}
}
return max_product;
}
}
关于java - 从数组中的三个整数中找到可以得到的最高乘积 - 如何使用蛮力求解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44628247/