1. 程式人生 > 實用技巧 >112買賣股票的最佳時機II

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]))