2016-10-29 7 views
0

問題を解決しようとしています。私たちはO(n)で配列のmaxProductを見つけることができるので、それはO(n²) であるので、許されるループの倍数はありません。私のコードでは、すべての要素が最初の最後の要素。私のコードのロジックを使用して、配列の最初と最後の要素をどのように乗算できますか?ここ配列の要素の掛け算

は私のコードです:

public class Maxprod { 
public static void main(String [] args){ 
    Maxprod myclass = new Maxprod(); 
    myclass.maxProduct(); 
} 

public void maxProduct(){ 
    int [] myarr = {4, -5, -7, 5}; 
    int max = 0, p=0; 
    int q = 0; 

    for(int i=0; i <myarr.length-1; i++){ 
     p = myarr[i]*myarr[i+1]; // 4 * 5 is missing here 
     if (p > max){ 
      max = p; 
     } 
    } 
    System.out.println(max); 
} 

} 

答えて

0

あなたのコードの状況は、あなたが思ったよりも悪いようです。 (4 * 5)だけでなく、(4 * -7)と(-5 * -5)も逃してしまいます。連続した数字だけが欲しいですか? forループの条件が1つずれているため、あなたも欠けています(-7 * 5)。

はにPを初期化し、あなたの最も直接的な質問に答えるために(開始*終了):

p = myarr[0] * myarr[myarr.length-1]; 
for(int i=0; i <myarr.length; i++){ 
    p = myarr[i]*myarr[i+1]; // 4 * 5 is missing here 
    if (p > max){ 
     max = p; 
    } 
} 
System.out.println(max); 

あなたが実際にmaxProductをしたい場合は、すべての順列を考慮すると、O(n)の中で、あなたが追跡する必要があります2つの最大正数と2つの最大負数。次のようなものを考えてみましょう:

public void maxProduct(){ 
    int [] myarr = {4, -5, -7, 5}; 
    int max = 0, maxn = 0, maxp = 0; 
    int n1 = 0, n2 = 0; 
    int p1 = 0, p2 = 0; 

    for(int i=0; i <myarr.length; i++){ 
     // Store greatest negative pair 
     if (myarr[i] < n1) { 
      n2 = n1; 
      n1 = myarr[i]; 
     } 

     // Store greatest positive pair 
     if (myarr[i] > p1) { 
      p2 = p1; 
      p1 = myarr[i]; 
     } 
    } 

    maxn = n1 * n2; 
    maxp = p1 * p2; 
    if (maxn > maxp) { 
     max = maxn; 
    } else { 
     max = maxp; 
    } 

    System.out.println(max); 
} 
関連する問題