[javascript] 주식시장에서 가장 큰 이익은 얼마일까요?

정은경·2020년 1월 6일
0

문제

  • 문제

prices는 배열이며, 각 요소는 매일의 주식 가격입니다.
만약 한 번만 거래할 수 있다면 = 사고 팔 수 있다면,
제일 큰 이익은 얼마일까요?

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

나의 풀이

const maxProfit = prices => {
  rlt = 0
  max = 0
  
  for(i = 0; i<(prices.length);i++){
    console.log("====="+i)
    temp =i+1
    for(j=temp;j<(prices.length);j++){
      //console.log(i+"&"+j)
      rlt = prices[j]-prices[i];
      console.log(rlt)
      if(max < rlt){
        max = rlt;
      }
    }
  }
  console.log(max)
  return max
    
};

maxProfit([7,6,5,4,3,1])

모법답안

const maxProfit = prices => {
    var min = Number.MAX_SAFE_INTEGER; 
    var max = 0;
    for (var i = 0; i < prices.length; i++) {
        min = Math.min(min, prices[i]);
        max = Math.max(max, prices[i] - min);
    }
    return max;
};
profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글