112买卖股票的最佳时机II

from typing import List
# 这道题和上一题很类似,但有一些不同,每天都可以买入,或者卖出
# 那么利润最大化,就是i + 1 天的价格比i天的价格高的时候买入
# 然后在i + 1天卖出
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 天数小于等于1的时候没有办法交易买卖
if len(prices) <= 1:return 0
max_profit = 0
for index in range(1,len(prices)):
# 当天比前一天价钱高的时候就买
if prices[index] > prices[index - 1]:
max_profit += prices[index] - prices[index - 1]
# 注意这里索引要加2
index += 2
return max_profit
A = Solution()
print(A.maxProfit([1,2,3,4,5,6]))
posted @ 2020-07-01 16:40  月为暮  阅读(230)  评论(0编辑  收藏  举报