|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ |
| 3 | + |
| 4 | +You are given an array prices where prices[i] is the price of a given stock on the ith day. |
| 5 | +Find the maximum profit you can achieve. You may complete as many transactions as you like |
| 6 | +(i.e., buy one and sell one share of the stock multiple times) with the following restrictions: |
| 7 | +After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). |
| 8 | +Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). |
| 9 | + |
| 10 | + |
| 11 | +Example 1: |
| 12 | +Input: prices = [1,2,3,0,2] |
| 13 | +Output: 3 |
| 14 | +Explanation: transactions = [buy, sell, cooldown, buy, sell] |
| 15 | + |
| 16 | +Example 2: |
| 17 | +Input: prices = [1] |
| 18 | +Output: 0 |
| 19 | + |
| 20 | +Constraints: |
| 21 | +1 <= prices.length <= 5000 |
| 22 | +0 <= prices[i] <= 1000 |
| 23 | +""" |
| 24 | +class Solution: |
| 25 | + def maxProfit(self, prices: List[int]) -> int: |
| 26 | + if len(prices) < 2: |
| 27 | + return 0 |
| 28 | + """ |
| 29 | + Reference: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75931/Easiest-JAVA-solution-with-explanations |
| 30 | + buy[i] = Math.max(buy[i - 1], sell[i - 2] - prices[i]); |
| 31 | + sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]); |
| 32 | + |
| 33 | + Let b2, b1, b0 represent buy[i - 2], buy[i - 1], buy[i] |
| 34 | + Let s2, s1, s0 represent sell[i - 2], sell[i - 1], sell[i] |
| 35 | + Then arrays turn into Fibonacci like recursion: |
| 36 | + |
| 37 | + b0 = Math.max(b1, s2 - prices[i]); |
| 38 | + s0 = Math.max(s1, b1 + prices[i]); |
| 39 | + """ |
| 40 | + b0 = b1 = -prices[0] |
| 41 | + s0 = s1 = s2 = 0 |
| 42 | + |
| 43 | + for i in range(1, len(prices)): |
| 44 | + b0 = max(b1, s2 - prices[i]) |
| 45 | + s0 = max(s1, b1 + prices[i]) |
| 46 | + b1, s1, s2 = b0, s0, s1 |
| 47 | + |
| 48 | + return s0 |
0 commit comments