解答
def maxProfit(prices):
n = len(prices)
if n <= 1:
return 0
buy = prices[0]
max_profit = [0]
profit = 0
for i in range(1, n):
# buy
if prices[i] < buy:
profit = max(max_profit)
buy = prices[i]
else:
profit = profit + (prices[i] - buy)
max_profit.append(profit)
buy = prices[i]
return max(max_profit)
2.贪心算法
def maxProfit(prices):
n = len(prices)
profit = 0
for i in range(n-1):
tmp = prices[i+1]-prices[i]
if tmp > 0:
profit += tmp
else:
continue
return profit
空间复杂度更小,O(1)