LeetCode Day 51 Dynamic Programming (12/17)
Published:
Last day of practice on stock trading problems!
Question 1
309. Best Time to Buy and Sell Stock with Cooldown
You are given an array
priceswhereprices[i]is the price of a given stock on theithday.Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
- After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Compared to LC122, this question adds a freeze period, so there are four states:
- State 1: Holding stock state (buying the stock today, or buying the stock before and then not acting on it and holding it) Not holding the stock state, and here there are two sell stock states
- State 2: Hold Sell Stock status (sold the stock two days ago to get through a one-day freeze. Or the day before is the sell stock status, has not been operated)
- State 3: Sell the stock today
- State 4: Frozen status today, but the frozen status is not sustainable and only lasts for one day!
So the code is as follows, the process of dp can correspond to these states.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n == 0:
return 0
dp = [[0] * 4 for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], max(dp[i-1][3], dp[i-1][1]) - prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][3])
dp[i][2] = dp[i-1][0] + prices[i]
dp[i][3] = dp[i-1][2]
return max(dp[n-1][3], dp[n-1][1], dp[n-1][2])
Question 2
714. Best Time to Buy and Sell Stock with Transaction Fee
You are given an array
priceswhereprices[i]is the price of a given stock on theithday, and an integerfeerepresenting a transaction fee.Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note:
- You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
- The transaction fee is only charged once for each stock purchase and sale.
Compared to LC122, this question just needs to subtract the commission when calculating the sell operation, the code is almost the same.
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
dp = [[0] * 2 for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i] - fee)
return max(dp[-1][0], dp[-1][1])
