3573. Best Time to Buy and Sell Stock V

RexiaN·2025년 12월 17일

자주 나오는 주식 팔기 문제. 이번에는 공매도가 추가된 전략이다. 기존의 k 번 매도 전략에 short 만 추가해서 해봤는데 바로 통과했다. 공매도는 매수 시 +를 해준다는 법만 기억하면 될 것 같다.

function maximumProfit(prices: number[], k: number): number {
    let closed = Array.from({ length: k + 1 }, () => -1000000000)
    let long = Array.from({ length: k + 1 }, () => -1000000000)
    let short = Array.from({ length: k + 1 }, () => -1000000000)

    closed[0] = 0;

    for (const p of prices) {
        let nextClosed = [...closed]
        let nextLong = [...long]
        let nextShort = [...short]

        for (let i = 1; i <= k; i++) {
            nextClosed[i] = Math.max(closed[i], long[i] + p, short[i] - p);
            nextLong[i] = Math.max(long[i], closed[i - 1] - p)
            nextShort[i] = Math.max(short[i], closed[i - 1] + p);
        }

        closed = nextClosed
        long = nextLong
        short = nextShort
    }

    return Math.max(...closed)
};

profile
Don't forget Rule No.1

0개의 댓글