题目
给定一个数组,元素表示每天 的股票价格,进行一次交易(先买再卖),问如何能够得到最大利润。
示例:
nums = [4,1,4,7,8,1],
输出:7
题解:
要想得到最大,就是前后差值最大,也就是找到,最小值和最大值
代码实现:
def maxProfit(prices):
if len(prices) < 2:
return 0
minPrice = prices[0]
max_profit = 0
for price in prices:
if price < minPrice:
minPrice = price
if price - minPrice > max_profit:
max_profit = price - minPrice
return max_profit
prices = [4,1,4,7,8,1]
maxProfit(prices)
Out[1]: 7
代码简化
def maxProfit(prices):
if len(prices) < 2:
return 0
minPrice = prices[0]
max_profit = 0
for i in range(len(prices)):
max_profit = max(max_profit,prices[i]-minPrice)
minPrice = min(minPrice,prices[i])
return max_profit
prices = [4,1,4,7,8,1]
maxProfit(prices)
Out[2]: 7