Scribbling

LeetCode: 188. Best Time to Buy and Sell Stock IV 본문

Computer Science/Coding Test

LeetCode: 188. Best Time to Buy and Sell Stock IV

focalpoint 2021. 11. 4. 18:11

LeetCode에서 푼 문제 중 가장 어려웠다...

당연히 빡대가리 내 머리로는 못 풀었고, 다른 사람 풀이 보고 이해하는 데에도 한참 걸렸다.

DP로 풀어야하는데, 점화식은 아래와 같다. O(NK)

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/655837/Python-Very-Detailed-Explanation-with-thought-process-DP

위 점화식에 대한 예제이다.

P = [3, 3, 5, 0 0, 3, 1, 4], K = 3

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        if not prices:
            return 0
        n = len(prices)
        dp = [[0] * (n) for _ in range(k+1)]
        ret = 0
        for i in range(1, k+1):
            prevprofit = -prices[0]
            for j in range(1, n):
                prevprofit = max(prevprofit, dp[i-1][j] - prices[j])
                dp[i][j] = max(dp[i][j-1], prevprofit + prices[j])
                ret = max(ret, dp[i][j])
        return ret