題目:
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。 設計一個算法來計算你所能獲取的最大利潤。你可以盡可能地完成更多的交易(多次買賣一支股票)。 注意:你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。
思路:
動態規划
在某教育科技公司面試時做過,筆試兩輪結束后,問做過的項目,我是做大數據的,面試官說該公司招圖像和NLP的,氣氛很尷尬,希望以后人力可以多張點心,不要整這種費時間費力的事情了。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length <= 1:
return 0
buy = prices[0]
auxiliary = [0] * length
for index in range(1, length):
if prices[index - 1] >= prices[index]:
buy = min(buy, prices[index])
auxiliary[index] = auxiliary[index - 1]
continue
else:
auxiliary[index] = auxiliary[index - 1] + (prices[index] - prices[index - 1])
result = auxiliary[length - 1]
return result
