WeCode Kata Day 17


質問する
価格は並び、各要素は毎日の株価です.一度しか取引できない=売買できるなら、最大の利益はいくらですか?
Input: [7,1,5,3,6,4]
Output: 5
설명: 2(가격=1)에 샀다가 5(가격=6)에 파는 것이 6-1이라 제일 큰 수익 7-1=6 은 안 된다. 먼저 사야 팔 수 있다.

Input: [7,6,4,3,1]
Output: 0
설명: 여기서는 매일 가격이 낮아지기 때문에 거래가 없다. 그래서 0이다.
Thinking Algorithm
  • は最大の利益を発表した.
  • ダブルfor文は、後の数字から前の数字を引いた値を1番の値と比較し、より大きな値を1番に割り当てます.
  • は、
  • 1回の値を返します.
  • Code
    const maxProfit = prices => {
      let max = 0;
    
      for(let i=0; i<prices.length-1; i++){
        for(let j=i+1; j<prices.length; j++){
          if(prices[j]-prices[i] > max) {
            max = prices[j]-prices[i];
          }
        }
      }
      return max;
    };