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])
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]
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