给定一个列表,它的第 i 个元素是一支给定股票第 i 天的价格。
如果最多只允许完成一笔交易(即买入和卖出一支股票,并规定每次只买入或卖出1股,或者不买不卖),请计算出所能获取的最大收益。
注意:不能在买入股票前卖出股票。
例如:
def get_max_profit(prices):
if len(prices) == 0 or len(prices) == 1:
return 0
max_profit = 0
min_price = prices[0]
for i in range(1, len(prices)):
max_profit = max(prices[i] - min_price, max_profit)
min_price = min(prices[i], min_price)
return max_profit
stock_prices1 = [7, 12, 1, 5, 9, 3, 11, 6, 4, 10]
stock_prices2 = [7, 1, 5, 3, 6, 4]
stock_prices3 = [7, 6, 4, 3, 1]
print("股票最大收益1为:{}".format(get_max_profit(stock_prices1))) # 最大收益 10
print("股票最大收益2为:{}".format(get_max_profit(stock_prices2))) # 最大收益 5
print("股票最大收益3为:{}".format(get_max_profit(stock_prices3))) # 最大收益 0
给定一个列表,它的第 i 个元素是一支给定股票第 i 天的价格。
如果可以尽可能地完成更多的交易(允许多次买卖一支股票,并规定每次只买入或卖出1股,或者不买不卖),请计算出所能获取的最大收益。
注意:不能同时进行多笔交易(必须在再次购买前卖出之前的股票)
例如:
def get_max_profit(prices):
if (len(prices) == 0) or (len(prices) == 1):
return 0
max_profit = 0
for i in range(1, len(prices)):
if prices[i] - prices[i - 1] > 0:
max_profit += prices[i] - prices[i - 1]
return max_profit
stock_prices1 = [7, 12, 1, 5, 9, 3, 11, 6, 4, 10]
stock_prices2 = [7, 1, 5, 3, 6, 4]
stock_prices3 = [7, 6, 4, 3, 1]
print("股票最大收益1为:{}".format(get_max_profit(stock_prices1))) # 最大收益 27
print("股票最大收益2为:{}".format(get_max_profit(stock_prices2))) # 最大收益 7
print("股票最大收益3为:{}".format(get_max_profit(stock_prices3))) # 最大收益 0
原文:https://www.cnblogs.com/wintest/p/13765429.html