LeetCode 코딩 문제 2020/12/14 - Best Time to Buy and Sell Stock II

이호현·2020년 12월 14일
0

Algorithm

목록 보기
33/138

[문제]

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

(요약) 배열 앞 요소부터 진행하면서 주식 사고 팔듯이 작은 숫자에서 그거보다 큰 숫자를 만났을 때 차이의 합을 누적해라.

[풀이]

var maxProfit = function(prices) {
  const length = prices.length;
  let profit = 0;
  let buy = Math.max(...prices);
 
  for(let i = 0; i < length - 1; i++) {
    buy = prices[i] < buy ? prices[i] : buy;

    if(buy < prices[i + 1]) {
      profit += prices[i + 1] - buy;
      buy = prices[i + 1];
    }
  }

  return profit;
};

배열 중 가장 큰 수를 찾고, index 0번째 부터 순회하면서 현재 갖고 있는 숫자보다 작으면 할당하고, 그 다음 요소가 그것보다 크면 숫자 차이를 누적.

profile
평생 개발자로 살고싶습니다

0개의 댓글