gpt4 book ai didi

java - 找到成对产品的最大和

转载 作者:行者123 更新时间:2023-12-01 11:17:47 27 4
gpt4 key购买 nike

我正在解决 java 中的一个问题,其中我必须找到 2 个整数数组的最大成对乘积。

示例:

array 1 -> [1, 3, -5]
array 2 -> [-2, 4, 1]

output: 23 // (3 * 4) + (1 * 1) + (-5 * -2)

我当前的代码也会产生这个输出。

我的解决方案

对两个数组进行排序,然后将两个数组中相同索引处的数字相乘,并对每对的乘积求和。

问题

我的解决方案是使用我不知道的测试用例进行测试的。我的解决方案无法通过所有测试用例。我不确定是否有任何输入会导致我的解决方案失败。

问题

我对给定问题的解决方案是否有问题阻止我的代码通过所有测试用例?

代码
private static long maxSum(int[] a, int[] b) {
long result = 0;

Arrays.sort(a);
Arrays.sort(b);

for (int i = a.length - 1; i >= 0; i--) {
result += a[i] * b[i];
}

return result;
}

问题描述

enter image description here

最佳答案

我想我知道问题出在哪里,但无法与法官联系,我无法确定。考虑 a[i] = 10^5 的情况和 b[i] = 10^5 ,问题中允许的最大值,现在 a[i] * b[i] = 10^10 .自 ab是整数类型,中间结果存储为整数。由于数字 10^10 超出了 int 的限制,您将得到溢出。

要解决此问题,您可以将数组值强制转换为 long。
result += Long.valueOf(a[i]) * Long.valueOf(b[i]);

关于java - 找到成对产品的最大和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62233910/

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