为这个分治解决方案添加记忆化

2024-10-01 04:44:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解决以下问题

问:K交易中的最大利润,即在不同的交易日,在给定一系列股价的情况下,必须买卖一只股票

对于输入[5,11,3,50,60,90],算法应该在5买入,在11卖出,然后在3买入,在90卖出,对于K=2交易,给出93的答案(11-3=6和90-3=87,6+87=93)

我已经想出了一个分而治之的算法,但无法想出如何将记忆添加到这个算法中。我试着只使用一个名为“利润”的数组,但它不起作用

我需要一些帮助,谢谢

def max_profits(prices, index, profit, transactions, maxTransactions, isBought):

    if(transactions == maxTransactions):
        return profit

    if(index > len(prices) - 1):
        return profit

    buy = 0
    sell = 0
    if(not isBought):
        buy = max_profits(prices, index + 1, profit - prices[index], transactions, maxTransactions, True)
    else:
        sell = max_profits(prices, index + 1, profit + prices[index], transactions + 1, maxTransactions, False)
    dont_sell_or_buy = max_profits(prices, index + 1, profit, transactions, maxTransactions, isBought)

    return max(buy, sell, dont_sell_or_buy)


if __name__ == "__main__":
    maxTransactions = int(input())
    inp = list(map(int, input().split()))
    print(max_profits(inp, 0, 0, 0, maxTransactions, False))

Tags: 算法indexreturnifbuy交易maxprices