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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM