問題是 鑑於整數數組和長度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