代码随想录第40天
121. 买卖股票的最佳时机
class Solution:
def maxProfit(self, prices: List[int]) -> int:
cost, profit = float('+inf'), 0
for price in prices:
cost = min(cost, price)
profit = max(profit, price - cost)
return profit
122.买卖股票的最佳时机II
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
tmp = prices[i] - prices[i - 1]
if tmp > 0: profit += tmp
return profit
123.买卖股票的最佳时机III
class Solution:
def maxProfit(self, prices: List[int]) -> int:
k = 2
f = [[-inf] * 2 for _ in range(k + 2)]
for j in range(1, k + 2):
f[j][0] = 0
for p in prices:
for j in range(k + 1, 0, -1):
f[j][0] = max(f[j][0], f[j][1] + p)
f[j][1] = max(f[j][1], f[j - 1][0] - p)
return f[-1][0]
原文地址:https://blog.csdn.net/weixin_43631425/article/details/144358684
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!