Say you have an array for which the ith elementis the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may completeat most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sellthe stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creatingall test cases.
这一题看到题目就应该可以想到DP
不过当我使用我自己一开始的DP思想的时候,内存超了,因为题目中给的数据可能非常的大,所以需要优化内存,
使用last[i][j]表示取0~i天的股票价格,最多交易j次,在第i天完成最后一次交易可以获得的最大收益,grabal[i][j]表示取0~i天的股票价格,最多交易j次,在第i天之前(包括第i天)完成最后一次交易可以获得的最大收益
那么有递推公式
last[i][j] =max(max(0, grabal[i - 1][j - 1] + max(prices[i] - prices[i - 1], 0)), last[i -1][j] + prices[i] - prices[i - 1]);
grabal[i][j] =max(grabal[i - 1][tmp], last[i][j]);
这里使用的是两个二维数组,如果不进行优化的话,内存会超,所以需要把两个二维数组优化为两个2*k或者是2*n的二维数组
不过即使优化时间还是有可能会超时
经过分析会发现,当k>=(n+1)/2的时候,可以在prices数组上取任意组合,也就是可以交易任意次,任意交易方案都可以实现,交易不受k次数的限制,问题退化为在原数组上找到最优的方案,因此直接遍历一遍Prices数组,找出最优方案即可,O(n)的时间即可实现
int maxProfit2(vector<int>& prices){
int result = 0;
int n = prices.size();
for(int i = 1; i < n; i ++){
if(prices[i] > prices[i-1])
result += (prices[i] - prices[i-1]);
}
return result;
}
int maxProfit(int k, vector<int>& prices)
{
int n = prices.size();
if(n <= 0||k<=0) return 0;
if(k >=(n+1)/2 ) return maxProfit2(prices);
vector<vector<int> > grabal(n+1,vector<int>(2,0));
vector<vector<int> > last(n+1,vector<int>(2,0));
int tmp = 0;
for (int j = 1;j<=k;j++)
for (int i = 1;i<n;i++)
{
tmp = j % 2;
int adfjp = last[i - 1][(tmp - 1) == -1 ? 1 : 0] + prices[i] - prices[i - 1];
last[i][tmp] = max(max(0, grabal[i - 1][(tmp - 1) == -1 ? 1 : 0] + max(prices[i] - prices[i - 1], 0)), last[i - 1][tmp] + prices[i] - prices[i - 1]);
grabal[i][tmp] = max(grabal[i - 1][tmp], last[i][tmp]);
}
return grabal[n - 1][k % 2];
}