2017-05-20 4 views
-1
char first = target[targetOffset]; 
    int max = sourceOffset + (sourceCount - targetCount); 

    for (int i = sourceOffset + fromIndex; i <= max; i++) { 
     /* Look for first character. */ 
     if (source[i] != first) { 
      while (++i <= max && source[i] != first); 
     } 

     /* Found first character, now look at the rest of v2 */ 
     if (i <= max) { 
      int j = i + 1; 
      int end = j + targetCount - 1; 
      for (int k = targetOffset + 1; j < end && source[j] == 
        target[k]; j++, k++); 

      if (j == end) { 
       /* Found whole string. */ 
       return i - sourceOffset; 
      } 
     } 
+1

いいえ最小番号が最大番号の前にある限り、値の最大の差を取得しようとしています。価格が最も高い番号から始まるので、「最大」は機能しません。私は配列の値を比較する方法を知らないのですか? –

+2

最大利益は11で短くなり、1でカバーします。;-) [* reduce *]の仕事のようです(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)。 – RobG

+0

@ jfriend00さんが効率的に削除する質問を編集しました - これで十分かどうか教えてください。 –

答えて

4

これは、(n)はOで解決することができます。

function getMaxProfit(prices) { 
    let min = prices[0]; 
    let profit = 0; 
    for (let i = 1; i < prices.length; i++) { 
     if (prices[i] < min) 
      min = prices[i]; 
     if (prices[i] - min > profit) 
      profit = prices[i] - min; 
    } 
    return profit; 
} 

アイデアは、位置私の前に最高の分を取得するために最初から最後までスキャンされます。この分は、i日(即時)に売ることによって得られる最高の利益を計算するために使用され、この金額はグローバル(最大)利益と比較されます。

関連する問題