买卖股票问题

Most consistent ways of dealing with the series of stock problems

T[i][k][0]: denotes the maximum profit on the i-th day with at most k transactions and with 0 stock in our hand after taking actions

T[i][k][1]: denotes the maximum profit on the i-th day with at most k transactions and with 1 stock in our hand after taking the action

Base cases:
T[-1][k][0] = 0, T[-1][k][1] = -Infinity
T[i][0][0] = 0, T[i][0][1] = -Infinity

Recurrence relation:
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])

k=arbitrary

class Solution:
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0

        n=len(prices)

        #T[i][k][0]=max(T[i-1][k][0],T[i-1][k][1]+prices[i])  # rest or sell
        #T[i][k][1]=max(T[i-1][k][1], T[i-1][k-1][0]-prices[i]) # rest or buy
        if k>=n//2: # equivalent ro k=+infinity
            #T[i][k][0]=max(T[i-1][k][0],T[i-1][k][1]+prices[i])  # rest or sell
            #T[i][k][1]=max(T[i-1][k][1], T[i-1][k][0]-prices[i]) # rest or buy
            T_ik0=0
            T_ik1=-float('inf')

            for p in prices:
                T_ik0_old=T_ik0
                T_ik0=max(T_ik0,T_ik1+p)
                T_ik1=max(T_ik1,T_ik0_old-p)

            return T_ik0

        T_ik0=[0]*(k+1)
        T_ik1=[-float('inf')]*(k+1)
        for i in range(len(prices)):
            for j in range(k,0,-1):
                T_ik0[j]=max(T_ik0[j],T_ik1[j]+prices[i])
                T_ik1[j]=max(T_ik1[j],T_ik0[j-1]-prices[i])

        return T_ik0[-1]

k=+infinity but with cooldown

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        #original
        #T[i][k][0]=max(T[i-1][k][0],T[i-1][k][1]+prices[i])  rest or sell
        #T[i][k][1]=max(T[i-1][k][1],T[i-1][k][0]-prices[i]) rest or buy

        #modify
        #T[i][k][0]=max(T[i-1][k][0],T[i-1][k][1]+prices[i])  rest or sell
        #T[i][k][1]=max(T[i-1][k][1],T[i-2][k][0]-prices[i]) rest or buy

        T_ik0=0; T_ik0_pre=0
        T_ik1=-float('inf')
        for i in range(len(prices)):
            T_ik0_tmp=T_ik0
            T_ik0=max(T_ik0,T_ik1+prices[i])
            T_ik1=max(T_ik1,T_ik0_pre-prices[i])
            T_ik0_pre=T_ik0_tmp

        return T_ik0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值