[LeetCode] 121. Best Time to Buy and Sell Stock

ming0·2024년 4월 26일
0

코딩테스트

목록 보기
5/6
post-thumbnail

👿 문제 121. Best Time to Buy and Sell Stock

  1. 하루하루 주식에 대한 price가 주어진 배열이 있다.

  2. 언제 사고 언제 팔아야 제일 큰 이익을 볼 수 있는지 값을 return한다.

  3. 이익을 보지 못하면 0을 return 한다.

😈 풀이

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
    let minPrice = prices[0]
    let answer = 0;

    for (let i = 1; i < prices.length; i++) {
        let profit = prices[i] - minPrice

        if (profit < 0) {
            minPrice = prices[i]
            continue;
        }

        if (profit > 0 && answer < profit) {
            answer = profit
            continue;
        }
    }

    return answer;
};
  1. 배열의 첫번째 값을 minPrice, answer(이익)을 0으로 초기화한다.

  2. 1번째부터 순회하면서 이익이 0보다 작으면 minPrice를 prices[i]로 할당한다.

  3. 이익이 0보다 크고 answer보다 크다면 answer는 profit으로 할당한다.

  4. 최종 answer를 return!

시간 복잡도: O(n)
공간 복잡도: O(1)

✅ 1일1알

0개의 댓글