继续股票买卖的练习,但是今天难度比较高,LeetCode上也标注了是Hard。
123. Best Time to Buy and Sell Stock III
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 at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
虽然卖股票的次数从一次变成了两次,但比之前难了不少。一天可以选择不卖,也能选择卖一个或是两个,选择更加多样。
在选择递推公式的时候,达到dp[i][1]状态,有两个具体操作:
那么dp[i][1]究竟选 dp[i-1][0] - prices[i],还是dp[i - 1][1]呢?
一定是选最大的,所以 dp[i][1] = max(dp[i-1][0] - prices[i], dp[i - 1][1]);
同理dp[i][2]也有两个操作:
所以dp[i][2] = max(dp[i - 1][1] + prices[i], dp[i - 1][2])
同理可推出剩下状态部分:
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]);
- class Solution:
- def maxProfit(self, prices: List[int]) -> int:
- if len(prices) == 0:
- return 0
- dp = [[0] * 5 for _ in range(len(prices))]
- dp[0][1] = -prices[0]
- dp[0][3] = -prices[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]
188. Best Time to Buy and Sell Stock IV
You are given an integer array
priceswhereprices[i]is the price of a given stock on theithday, and an integerk.Find the maximum profit you can achieve. You may complete at most
ktransactions: i.e. you may buy at mostktimes and sell at mostktimes.Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
和前面的题相比,限制了交易次数。在二维递推数组中,可以发现,
除了0以外,偶数就是卖出,奇数就是买入。
题目要求是至多有K笔交易,那么j的范围就定义为 2 * k + 1 就可以了。
- class Solution:
- def maxProfit(self, k: int, prices: List[int]) -> int:
- if len(prices) == 0:
- return 0
- dp = [[0] * (2*k+1) for _ in range(len(prices))]
- for j in range(1, 2*k, 2):
- dp[0][j] = -prices[0]
- for i in range(1, len(prices)):
- for j in range(0, 2*k-1, 2):
- dp[i][j+1] = max(dp[i-1][j+1], dp[i-1][j] - prices[i])
- dp[i][j+2] = max(dp[i-1][j+2], dp[i-1][j+1] + prices[i])
- return dp[-1][2*k]