反反复复看了好几遍,终于算是看懂了。总结一下。
Therefore our definition of T[i][k] should really be split into two: T[i][k][0] and T[i][k][1], where the former denotes the maximum profit at the end of the i-th day with at most k transactions and with 0 stock in our hand AFTER taking the action, while the latter denotes the maximum profit at the end of the i-th day with at most k transactions and with 1 stock in our hand AFTER taking the action.
Recurrence relations:
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])
- 为什么sell的时候k不-1,buy的时候k-1?
因为buy和sell是成双成对的,我们这里只假设buy会消耗一次transaction,光sell是不算消耗了一次transaction的。 - 为什么k都是跟着sell和buy动作在变,但是0和1不跟着变?
可以这么理解,0和1是跟随i变化的。我们sell或buy,立刻会影响k,但是stock状态是和第几天有关。
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])
表示i-1天是没有stock的,在此状态下buy了,这一天的k就要减1,但是stock的状态是到下一天才生效。
- T[-1][k][0] = 0,
- T[-1][k][1] = -Infinity
- T[i][0][0] = 0,
- T[i][0][1] = -Infinity
- 交易不开始,手上也没股票,所以没profit
- 交易不开始,手上是不可能有股票的,所以不可能
- 不能交易(k=0),手上没股票,所以没profit
- 不能交易,手上怎么可能会持股呢,不可能(T[i][0][1]是T[i][-1][0]-price[i]得到的,T[i][-1][0]就不存在,这个解释不知道对不对)
If k is positive infinity, then there isn’t really any difference between k and k - 1 (wonder why? see my comment below), which implies T[i-1][k-1][0] = T[i-1][k][0] and T[i-1][k-1][1] = T[i-1][k][1].
在k是无穷大的时候,k的变化不再影响profit了。因为k大于n/2(n是数组长度),之后的buy和sell都是没有意义的。
(Note: The caching of the old values of T_ik0, that is, the variable T_ik0_old, is unnecessary.
这里还不懂,我感觉加上pre之后更好理解