基本上就是i个数j次数,每次不是i-1就是j-1。j-1就是决定当前这次怎么处理:数组里就是决定属于前堆还是当前堆,股票里就是当前卖不卖,要用当前减去之前某次。和Best Time to Buy and Sell Stock III 中left[i] = Math.max(prices[i] - minPrice, left[i-1]);不一样stock中价格相减,此处数字叠加。
股票问题
Therefore our definition ofT[i][k]should really be split into two:T[i][k][0]andT[i][k][1], where theformerdenotes the maximum profit at the end of thei-thday with at mostktransactions and with0stock in our hand AFTER taking the action, while thelatterdenotes the maximum profit at the end of thei-thday with at mostktransactions and with1stock in our hand AFTER taking the action. Now the base cases and the recurrence relations can be written as:
For the base cases,T[-1][k][0] = T[i][0][0] = 0has the same meaning as before whileT[-1][k][1] = T[i][0][1] = -Infinityemphasizes the fact that it is impossible for us to have1stock in hand if there is no stock available or no transactions are allowed.
总结用法:
可以左边遍历再右边遍历 Shortest Distance to a Character(必须数组因为返回数组),Longest Mountain in Array(可以优化数组为数字因为返回最大值)