问题是 鉴于整数数组和长度L,发现长度为L的子阵列使得所有整数的产品是最大的。 实施例: 输入:{4,1,-7,-8,9},3 输出:{-7,-8,9-}如何计算阵列的M个元素的最大产物与N个元素
我写了一个很粗地和逻辑地有缺陷的代码,其不给任何合理的输出。也许有人可以指向我在正确的方向
public class ProductProblem {
/*
* Given an array of integers and a length L, find a sub-array of length L such that the products of all integers are the biggest.
Example:
Input: {4, 1, -7, -8, 9}, 3
Output: {-7,-8,9}
*/
int a[];
int l;
int maxProduct;
public int findProduct(int[] input, int len,int product){
int[] output=new int[len];
for (int i=0;i<input.length;i++){
if(len>=1){
System.out.println(product);
System.out.println("input[i]="+input[i]);
product= product*input[i];
findProduct(input,len-1,product);
System.out.println("len="+len);
}
else {
return product;
}
}
if (product>maxProduct){
maxProduct=product;
}
return product;
}
public static void main(String[] args){
ProductProblem pp=new ProductProblem();
int[] a={1,3,-6,3,5};
pp.a=a;
int max=pp.findProduct(a,3,1);
System.out.println(max);
}
}
通过子阵你的意思是一个连续的子阵? – pkacprzak
哦拍我没有想到。我是假设它是不连续 – user3386479
问题的来源是这样的http://www.careercup.com/question?id=5752271719628800 – user3386479