티스토리 뷰

728x90

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/

 

Best Time to Buy and Sell Stock with Cooldown - LeetCode

Best Time to Buy and Sell Stock with Cooldown - You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell o

leetcode.com

https://www.youtube.com/watch?v=IGIe46xw3YY 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        def f(i, buy, prices, size, dp):
            if i >= size:
                return 0
            if dp[i][buy] != -1:
                return dp[i][buy]
            
            if buy == True:
                dp[i][buy] = max(
                        -prices[i] + f(i+1, False, prices, size, dp),
                        0 + f(i+1, True, prices, size, dp)
                    )
                return dp[i][buy]

            dp[i][buy] = max(
                        prices[i] + f(i+2, True, prices, size, dp),
                        0 + f(i+1, False, prices, size, dp)
                    )
            return dp[i][buy]
        
        size = len(prices)
        dp = []
        for i in range(size):
            dp.append({
                True: -1,
                False: -1
            })

        return f(0, True, prices, size, dp)
728x90

'공부' 카테고리의 다른 글

[git] semantic commit messages & semantic branch names  (0) 2023.02.04
[Python] mixin  (0) 2023.02.04
[airflow] providers packages reference  (0) 2023.02.02
[Jira] issue 이동 (other project)  (0) 2023.02.02
[postgres] AUTO INCREMENT  (0) 2023.02.02
댓글