题目:
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).
题意:
可以看到股票在连续n天的价格。设计一个算法去获取最大收益,最多完成k次交易。不同交易之间不许穿插进行,就是说不能手上有多只股票,最多只许有一只。
思路:
首先要记得一点,k次交易需要交易的天数是2k天,如果2k>n,那么很明显此问题就退化成了n天内随便交易多少次,因为n天你最多只能交易n/2次。
我们保存两个数组涌来做动态规划。第一个数组是hold[k],代表买入了某只股票,进入了第k次交易手上一共盈利了多少,就是前面k-1次股票交易结束了,现在手上还持有一份股票,所以进入了第k次交易。而另一个数组reverse[k]代表的是k次交易完成的情况下,手上的盈利的数目。
在进入第i天的时候,前面i-1天的从1次交易到k次交易的各个结果值会保存在hold和reverse数组中。此时就是状态转移方程的制定。对于第i天,进入第m次交易,就应该是前面完成m-1的交易的盈利(reverse[m-1])减去第i天的股价。如果是完成第m次交易,那么就应该是前面i-1天进入到第m次交易的手上的盈利加上第i天股票所卖得到的钱。
- hold[i][m] = max(hold[i-1][m], reverse[i-1][m - 1] - prices[i])
- reverse[i][m] = max(reverse[i-1][m], hold[i-1][m] + prices[i])
因为计算第i天的结果时只需要知道第i-1天的结果,所以可以只保存前一天的两个数组。
以上所述。
代码如下:
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int len = prices.size();
if(k > len/2)
{
int result = 0;
for(int i = 1; i < len; i++)
result += max(0, prices[i] - prices[i-1]);
return result;
}
vector<vector<int>> reserve(2, vector<int>(k + 1, 0));
vector<vector<int>> hold(2, vector<int>(k + 1, INT_MIN));
hold[0][1] = -prices[0];
int position = 0;
int last = 1;
for(int i = 0; i < len; i++)
{
for(int j = 1; j < k + 1; j++)
{
reserve[position][j] = max(reserve[last][j], hold[last][j] + prices[i]);
hold[position][j] = max(hold[last][j], reserve[last][j-1] - prices[i]);
}
last = position;
position = (position + 1) % 2;
}
return reserve[(position + 1) % 2][k];
}
};