Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
解法:
比较难想清楚的一题。
需要用到两个dp matrix, 一个叫local, 一个叫global
local[i][j] 表示的是前i天做j次操作,最后一次sell正好是i天时的最大利润
global[i][j]表示的是前i天做j次操作,最大的利润
那么答案就是global[N][k]
local的递推关系是:
local[i][j]可以是i-1天已经完成了j次交易,那么只要把最后一天的交易顺延,就得到了i天完成j次交易。另外一个可能是到i - 1天完成了j - 1次交易,那么只要再加上新加的一天的交易即可。
global的递推关系是:
global[i][j]是要么新一天的local maxi, 或者是前一天的global max