目录
学习目标
- 123.买卖股票的最佳时机III
- 188.买卖股票的最佳时机IV
学习内容
123.买卖股票的最佳时机III
123. 买卖股票的最佳时机 III - 力扣(LeetCode)
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
a,b,c,d = -prices[0],0,-prices[0],0
for i in range(n):
a = max(a,-prices[i])
b = max(b,a+prices[i])
c = max(c,b-prices[i])
d = max(d,c+prices[i])
return d
188.买卖股票的最佳时机IV
188. 买卖股票的最佳时机 IV - 力扣(LeetCode)
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
if k==0:return 0
dp = [0]*(2*k)
for i in range(2*k):
if i%2==0:
dp[i] = -prices[0]
for i in range(n):
for j in range(2*k):
if j%2==0:
if j==0:
dp[j] = max(dp[j],-prices[i])
else:
dp[j] = max(dp[j],dp[j-1]-prices[i])
else:
dp[j] = max(dp[j],dp[j-1]+prices[i])
return dp[-1]