题目:
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
法一:双循环遍历(超时)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = []
profit.append(0)
for i in range(len(prices)-1):
for j in range(i+1,len(prices)):
if prices[j] >= prices[i]:
subtract = prices[j] - prices[i]
profit.append(subtract)
return max(profit)
法二:一次遍历,寻找最大值(超时)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxP = 0
for i in range(0,len(prices)-1):
minV = prices[i]
maxV = max(prices[i+1:])
maxP = max(maxP,maxV-minV)
return maxP
法三:一次遍历,寻找最小值
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minprice = max(prices)
maxprofit = 0
for price in prices:
maxprofit = max(price - minprice, maxprofit)
minprice = min(price, minprice)
return maxprofit