为此分治法添加备忘录

我正在尝试解决以下问题

Q:在K笔交易中获得最大利润,也就是说,鉴于不同日期的一系列股票价格,必须买卖股票。

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

我想出了一个分而治之的算法,但是无法弄清楚如何为此添加备忘录。我尝试只使用一个名为profits的数组,但是它不起作用。

我可以帮忙,谢谢!

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],True)
    else:
        sell = max_profits(prices,profit + prices[index],transactions + 1,False)
    dont_sell_or_buy = max_profits(prices,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,False))
yuanxiao_001 回答:为此分治法添加备忘录

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2909517.html

大家都在问