java中的数组最大乘积子数组
这个问题是我写的解决方案的最大乘积子数组,但并没有得到确切的答案
package practicePrograms;
import java.util.*;
public class max_product_subarray {
public static void main(String[] args) {
int[] arr = {8, -2, -2, 0, 8, 0, -6, -8, -6, -1};
System.out.println(new Solun().maxProduct(arr, arr.length));
}
}
class Solun {
long maxProduct(int[] arr, int n) {
long max = 1;
long temp;
List<Integer> at = new ArrayList<>();
for (int i = 0; i < n; ) {
temp = max;
max = temp * arr[i];
if (max == 0) {
if (temp < 0) {
temp = temp * -1;
}
at.add((int) temp);
max = 1;
}
i++;
}
Collections.sort(at);
long maxi = at.get(at.size() - 1);
return maxi;
}
}
这里,ArrayList应该以排序方式包含[32, 8, 288]
,但它只包含[8, 32]
为什么不包含288
# 1 楼答案
@csalmhof已经用你的解决方案指出了错误。但以下是一个可行的解决方案,可能会对你有所帮助
如果你对工作有任何疑问,请告诉我