Python编程题8--股票最大收益

题目1

给定一个列表,它的第 i 个元素是一支给定股票第 i 天的价格。
如果最多只允许完成一笔交易(即买入和卖出一支股票,并规定每次只买入或卖出1股,或者不买不卖),请计算出所能获取的最大收益。
注意:不能在买入股票前卖出股票。

例如:

  • 列表为 [7, 1, 5, 3, 6, 4] ,那么在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,此时可得到最大收益为 6-1 = 5 。
  • 列表为 [7, 6, 4, 3, 1],此时如果进行交易,那么收益将为负,所以不买不卖,此时最大收益为 0。

实现思路

  • 设置代表最大收益的参数为 max_profit ,默认值为 0
  • 设置代表最小价格的参数为 min_price,默认值为第 1 天的股票价格
  • 从列表第 2 个元素开始,遍历价格列表 prices,遍历过程中,买入价格为 min_price ,每次的价格为 prices[i]
  • 每次的价格作为卖出价格,收益为 prices[i] - min_price,将当前卖出的收益与之前计算的最大收益 max_profit 比较,取较大值并重新赋值给 max_profit
  • 每次计算最大收益后,将当前卖出的价格 prices[i] 与之前的最小价格 min_price 比较,取较小值并重新赋值给 min_price

代码实现

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

题目2

给定一个列表,它的第 i 个元素是一支给定股票第 i 天的价格。
如果可以尽可能地完成更多的交易(允许多次买卖一支股票,并规定每次只买入或卖出1股,或者不买不卖),请计算出所能获取的最大收益。
注意:不能同时进行多笔交易(必须在再次购买前卖出之前的股票)

例如:

  • 列表为 [7, 1, 5, 3, 6, 4] ,那么在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出,紧接着在第 3 天(股票价格 = 3)的时候买入,在第 4 天(股票价格 = 6)的时候卖出,此时可得到最大收益为 (5-1) + (6-3) = 7 。
  • 列表为 [7, 6, 4, 3, 1],此时如果进行交易,那么收益将为负,所以不买不卖,此时最大收益为 0。

实现思路

  • 设置代表最大收益的参数为 max_profit ,默认值为 0
  • 从列表第 2 个元素开始,遍历价格列表 prices
  • 遍历过程中,当前价格为 prices[i] 看作卖出价格,上一个价格为 prices[i - 1] 看作买入价格,如果二者之差为正,则本次进行交易的收益大于0,于是便把本次收益添加到最大收益 max_profit 中

代码实现

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