您的位置:首页 > 其它

leetcode 188: Best Time to Buy and Sell Stock IV

2015-08-24 22:36 525 查看
Extended from the solution of Best Time to Buy and Sell Stock III. I have two states (last and curr), and each state has 2*k different steps. Steps 0
and 1 means the buy and sell for the first time; Steps 2 and 3 means the buy and sell for the second time, and so on. When you figure out how this works with k=2, you can understand this easily. Thus, the current buy dp[curr][2*j] depends on the last state's
sell dp[last][2*j-1] and last state's buy dp[last][2*j]. And the current sell dp[curr][2*j+1] depends on the last state's buy dp[last][2*j] and the last state's sell dp[last][2*j+1]. In the end, find out the maximum profit among all the sell profits. Because
the first buy and sell have no previous buy and sell, they need to be dealt with outside of the loop. If you do this process by hand, you will find out that the biggest profit will be in the index of the final sell and it is the accumulation of previous profits.

A trick of this problem is that k may be very big, which will result in a runtime error. So the thing here is when k is bigger or equal to the number of days, the situation becomes to I can buy and sell at any day. So the maximum profit will be the same
as Best Time to Buy and Sell Stock II.

class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
if(n<2||k==0)
return 0;
int res=0;
if(k>=n)//same as Best Time to Buy and Sell Stock II
{
for(int i=1;i<n;i++)
if(prices[i]>prices[i-1])
res+=prices[i]-prices[i-1];
return res;
}
int last=0,curr=1;
vector<int> a(2*k,0);
for(int i=0;i<2*k;i+=2)//initialize the buy to make sure the first buy can be started
a[i]=INT_MIN;
vector<vector<int> > dp(2,a);
for(int i=0;i<n;i++)
{
dp[curr][0]=max(dp[last][0],-prices[i]);//the first buy may start at day i
dp[curr][1]=max(dp[last][1],dp[last][0]+prices[i]);//compare the profits between sell today and not
for(int j=1;j<k;j++)
{
dp[curr][2*j]=max(dp[last][2*j],dp[last][2*j-1]-prices[i]);
dp[curr][2*j+1]=max(dp[last][2*j+1],dp[last][2*j]+prices[i]);
}
swap(curr,last);
}
for(int i=1;i<2*k;i+=2)
if(dp[last][i]>res)
res=dp[last][i];
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: