【发布时间】:2018-10-21 09:06:02
【问题描述】:
在给定 9 位数字的情况下,我试图找到产生最大产品的 3 个相邻数字。例如对于数字 198348756,我的解决方案应该返回 [8,7,5],因为它的乘积是 280,并且是可能的最大乘积。我的代码找到了最大乘积,但无法返回创建最大乘积的数字数组。相反,它返回它在 for 循环中检查的最后一个数组。我不明白为什么创建最大乘积的数字数组没有存储在变量结果中?
public class Solution {
ArrayList<Integer> digits = new ArrayList<>();
/// digits to int array
void tocharArray(String num) {
char[] charArray = num.toCharArray();
for (Character c : charArray) {
digits.add(Character.getNumericValue(c));
}
//System.out.println(digits);
//System.out.println(digits.size());
}
//gets product of array ex [1,2,3] ->6
int arrayproduct(ArrayList<Integer> array) {
int product = 1;
for(int i=0;i < array.size(); i++) {
product = product * array.get(i);
}
return product;
}
ArrayList<Integer> func() {
ArrayList<Integer> three = new ArrayList<>();
ArrayList<Integer> result = new ArrayList<>();
// array of the first 3 digits of the number
for(int index = 0; index < 3;index++) {
three.add(digits.get(index));
}
//initially the max product is the first 3 digits
int maxproduct = arrayproduct(three);
System.out.println(three); //from test [1,9,8]
System.out.println(maxproduct);// from test 72
ArrayList<Integer> copy = three;
for(int j = 3 ; j < digits.size();j++) {
copy.remove(0);
copy.add(digits.get(j));
int next = arrayproduct(copy);
System.out.println(copy);
if(next > maxproduct) {
maxproduct = next;
result = copy;
}
}
System.out.println(maxproduct); // returns 280 which is correct
System.out.println(result); // returns [7,5,6]
return result;
}
public static void main(String[] args) {
String test1 = "198348756";
Solution sol = new Solution();
sol.tocharArray(test1); \\[1,9,8,3,4,8,7,5,6]
sol.arrayproduct(sol.digits); \\returns [7,5,6] which is incorrect
sol.func();
}
}
【问题讨论】:
标签: java algorithm math numbers series