
😎풀이
- 매도(
sold
), 유지(hold
), 쿨다운(cooldown
) 선언
prices
순회
2-1. 이전 매도 금액 저장
2-2. 매도 금액은 유지 + 현재가 (매도의 경우)
2-3. 유지 금액은 유지 혹은 매수 중 최댓값으로 선택
2-4. 쿨다운은 이전 매도가 혹은 쿨다운 금액 중 최댓값으로 선택
- 매도 혹은 쿨다운(직전 판매)가 최댓값이므로 둘 중 더 큰 금액 반환
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)
};