描述
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).
分析
Best Time to Buy and Sell Stock的后继问题,这次彻底灵活了,可以买卖k次,同样任何时刻手上最多持有1股。
如果k > n / 2
其实就退化成了不限次数买卖的情况,就是系列中的第二题的情况。然后我们构造这样一个二维动态规划状态转移方程,令local[i][j]
为在截止第i天最多可j次交易并且最后一次交易在最后一天卖出的最大利润,global[i][j]
为在截止第i天时最多可j次交易的最大利润,目标就是global[n - 1][k]
。
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
global[i][j] = max(local[i][j], global[i - 1][j])
代码
Python
1 | class Solution(object): |