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).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
状态:
int Solve(vector<int>& prices)
{
int ans = 0;
for (int i = 1; i < prices.size(); i++)
if (prices[i] > prices[i - 1])
ans += prices[i] - prices[i - 1];
return ans;
}
int maxProfit(int k, vector<int>& prices) {
if(prices.size()<2||k<1)
return 0;
if (prices.size() <= 2*k)
return Solve(prices); //to Solve the time-out problem (k is too bigger than the size of current vector)
//与最多交易二次那道题同理,始终保证当前手里的收益最大即可;
//与III相比,该题的解法相当于扩展到:一个k次交易的循环即可
vector<int> buy(k,INT_MIN);
vector<int> sell(k,INT_MIN);
for(int i=0;i<prices.size();i++)
{
for(int j = 0;j<k;j++)
{
if(j==0)
buy[j]=max(buy[j],-prices[i]);
else
buy[j]=max(buy[j],-prices[i]+sell[j-1]);
sell[j]=max(sell[j],prices[i]+buy[j]);
}
}
return sell[k-1]; //手里剩余的最后的收益
}