[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown

Chobby·2025년 3월 8일
1

LeetCode

목록 보기
280/427

😎풀이

  1. 매도(sold), 유지(hold), 쿨다운(cooldown) 선언
  2. prices 순회
    2-1. 이전 매도 금액 저장
    2-2. 매도 금액은 유지 + 현재가 (매도의 경우)
    2-3. 유지 금액은 유지 혹은 매수 중 최댓값으로 선택
    2-4. 쿨다운은 이전 매도가 혹은 쿨다운 금액 중 최댓값으로 선택
  3. 매도 혹은 쿨다운(직전 판매)가 최댓값이므로 둘 중 더 큰 금액 반환
function maxProfit(prices: number[]): number {
    if(prices.length === 0) return 0
    let sold = 0
    let hold = -Infinity
    let cooldown = 0
    for(const price of prices) {
        const prevSold = sold
        sold = hold + price
        hold = Math.max(hold, cooldown - price)
        cooldown = Math.max(cooldown, prevSold)
    }
    return Math.max(sold, cooldown)
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글