Ideas: This problem has two solutions. Both solutions use dynamic programming. The first solution maintains three status for each stock so that it runs faster with the time complexity O(n). The second solution uses classical dynamic programming equation which runs slower with the time complexity O(n^2).
Solution 1
There are three actions: buy, sell and do nothing. Relatively there are three status: hold a stock, cooldown and can buy a stock. We can conclude that: hold[i] = max( hold[i-1], canBuy[i-1] - prices[i] )
. coolDown[i] =hold[i-1] + prices[i]
. canBuy[i] = max(coolDown[i-1], canBuy[i-1])
.
1 | def maxProfit1(prices) -> int: |
Solution 2
Compute the maximum value from back to front. Using two traversals, the first loop locates each stock and the second loop calculates the maximum profit that the current stock can make on each subsequent sale. The core equation is profit[i] = max(profit[i], prices[j] - prices[i] + profit[j + 2])
. And keep updating it profit[i] = max(profit[i], profit[i+1])
.
1 | def maxProfit(prices) -> int: |