【leetcode】Python實現-122.買賣股票的最佳時機II
阿新 • • 發佈:2018-12-24
122.買賣股票的最佳時機II
描述
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
設計一個演算法來計算你所能獲取的最大利潤。你可以儘可能地完成更多的交易(多次買賣一支股票)。
注意:你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。
示例1
輸入: [7,1,5,3,6,4]
輸出: 7
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 3 天(股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5-1 = 4 。
隨後,在第 4 天(股票價格 = 3)的時候買入,在第 5 天(股票價格 = 6)的時候賣出, 這筆交易所能獲得利潤 = 6-3 = 3 。
示例2
輸入: [1,2,3,4,5]
輸出: 4
解釋: 在第 1 天(股票價格 = 1)的時候買入,在第 5 天 (股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接連購買股票,之後再將它們賣出。
因為這樣屬於同時參與了多筆交易,你必須在再次購買前出售掉之前的股票。
示例3
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤為 0。
我
profit = 0
i = 0
while i < len(prices)-1:
minimum = prices[i]
j = i+1
if prices[i] >= prices[j]:
minimum = min(prices[j], minimum)
i+=1
else:
while j <= len(prices)-1:
if j == len(prices)-1 :
profit+=prices[j] - minimum
return profit
elif prices[j] <= prices[j+1]:
j+=1
else:
profit+=prices[j]-minimum
i = j+1
break
return profit
終於又靠自己通過了,這感覺真爽。
看看別人的。真的強,邏輯。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i]-prices[i-1]
return profit
比如[1,3,5,2,6,1,3]
profit=(3-1)+(5-3)+(6-2)+(3-1)=3-1+5-3+(6-2)+(3-1)=(5-1)+(6-2)+(3-1)
而我的是直接求解profit = (5-1)+(6-2)+(3-1)