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];
}