让:
dp[i, j] = maximum worth obtainable at period i if we currently hold
stock j
假设t[i] = transaction cost at period i
。
我们有:
dp[0, A] = A[0] # buy the best at time 0
dp[0, B] = B[0] # you said only buying A and selling B induces a cost,
# you didn't say buying B induces a cost. If it does,
# just subtract t accordingly below
dp[i, A] = max(
dp[i - 1, B] + A[i] - t[i], # sell B, buy A
A[i] # buy A alone
) # we buy A no matter what
dp[i, B] = max(
dp[i - 1, A] + B[i], # sell A, buy B, - t[i] if needed
B[i] # buy B alone
)
答案是:
max{dp[i, A], dp[i, B]}
i