tasks for today: (买卖股票专题)
1. 121.买卖股票的最佳时机
2. 122.买卖股票的最佳时机II
3. 123.买卖股票的最佳时机III
----------------------------------------------------------------------------------
1. 121.买卖股票的最佳时机
In this practice, the dp list signifies: dp[i][0]: the i-th day, how much money do you have at most if you do hold the stock, while dp[i][1] signifies how much money do you have at most if you do not hold the stock.
pay attention to the condition of buying the stock, which will make the money be negative.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 1:
return 0
dp = [[0] * 2 for _ in range(len(prices))]
dp[0][0] = -prices[0]
dp[0][1] = 0
for i in range(1, len(prices)):
dp[i][0] = max(dp[i-1][0], -prices[i])
dp[i][1] = max(dp[i-1][1], dp[i][0] + prices[i])
return dp[-1][1]
2. 122.买卖股票的最佳时机II
In this practice, we have met it in the greedy algorithm topic, when using the dp method, the key difference of setting from last practice 121, is that the stock can be traded in/out multiple times with requirement of adhering in-out-in-out (not in-in-out-out or similar sequence), this leads to a minor change in the code, which presents on the dp update equation of dp[i][0], repalcing the -prices[i] with dp[i-1][1]-prices[i].
This is because, due to the allowing of multiple trading, when buying in the stock, there might be some existing profit in pocket, which is 0 in practice 121 where only single trading is allowed.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 1: return 0
if len(prices) == 2: return max(0, prices[1] - prices[0])
dp = [[0] * 2 for _ in range(len(prices))]
dp[0][0] = -prices[0]
dp[0][1] = 0
for i in range(1, len(prices)):
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])
return dp[-1][1]
3. 123.买卖股票的最佳时机III
In this practice, the key difference from the practice 122 is the limitation on the times of the trading, which presents as there is a limit on the maximum times of trading, buyers get to decide how many times of trading in/out as long as not exceeding the maximum limits.
This difference leads to the extension of the 2-dim of the dp table, which recording the condition of each time's trading in or trading out.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 1: return 0
if len(prices) == 2: return max(0, prices[1] - prices[0])
dp = [[0] * 5 for _ in range(len(prices))]
dp[0][0] = 0
dp[0][1] = -prices[0]
dp[0][2] = 0
dp[0][3] = -prices[0]
dp[0][4] = 0
for i in range(1, len(prices)):
dp[i][0] = dp[i-1][0]
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i])
dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i])
dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i])
return dp[-1][4]