LC练习 买卖股票的最佳时机
解答
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length= len(prices)
i = 0
j = 1
profit = 0
while j <= length - 1:
if prices[i] < prices[j]:
if j == length-1:
profit += prices[j] - prices[i]
break
else:
while prices[j] < prices[j+1]:
j = j + 1
if j == length-1:
break
profit += prices[j] - prices[i]
i = j + 1
j = j + 2
else:
i = i + 1
j = j + 1
return profit
首先找到差价点对i
和j
,如果价格持续升高,则j=j+1
;否则,计算收益,再寻找差价对。