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).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
题意:
与123. Best Time to Buy and Sell Stock III不同,可以买卖k次。
思路:
实质上就是122. Best Time to Buy and Sell Stock II和123. Best Time to Buy and Sell Stock III的结合。
大致上与前一题相同,都是找状态转移方程。只不过需要注意的是,如果k>n/2,这就是122. Best Time to Buy and Sell Stock II的情况,那么就可以自由交易,即可以买卖相间,所以对于有利益的,我们就进行一次买卖,亏损的就不买卖了,利润为0。否则对于一般的情况,可以用123. Best Time to Buy and Sell Stock III的思路。
此外特别注意的是:k可能很大,所以最好不要用profit数组,用一个vector来保存,才不会runtime error。
代码:
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(k<=0)
return 0;
//int profit[2*k];
vector<int>profit;
int n=prices.size();
int maxprofit=0;
if(k>n/2)
{
for(int i=1;i<n;i++)
maxprofit+=max(prices[i]-prices[i-1],0);
return maxprofit;
}
for(int i=0;i<2*k;i++)
{
profit.push_back(INT_MIN);
profit.push_back(0);
}
for(int i=0;i<n;i++)
{
for(int j=2*k-1;j>=0;j--)
{
if(j!=0)
{
if(j%2==1)
profit[j]=max(profit[j],profit[j-1]+prices[i]);
else
profit[j]=max(profit[j],profit[j-1]-prices[i]);
}
else
profit[j]=max(profit[j],-prices[i]);
}
}
for(int i=1;i<=2*k-1;i+=2)
{
maxprofit=max(profit[i],maxprofit);
}
return maxprofit;
}
};