Best Time to Buy and Sell Stock with Cooldown
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2] Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
class Solution {
public:
// int findprofit(vector<int> prices,int i,int n,vector<int> &dp)
// {
// if(i>=n)return 0;
// if(dp[i]!=-1) return dp[i];
// int maxval=0;
// for(int j=i+1;j<n;++j)
// if(prices[i]<prices[j])
// maxval=max(maxval,(prices[j]-prices[i])+findprofit(prices,j+2,n,dp));
// maxval=max(maxval,findprofit(prices,i+1,n,dp));
// dp[i]=maxval;
// return maxval;
// }
int maxProfit(vector<int>& prices) {
int n=prices.size();
// vector<int> dp(n+1,-1);
// return findprofit(prices,0,n,dp);
if(n<=1) return 0;
int ans[3][n];
ans[0][0]=0;
ans[1][0]=-prices[0];
ans[2][0]=0;
for(int i=1;i<prices.size();++i)
{
ans[0][i]=max(ans[0][i-1],ans[2][i-1]);
ans[1][i]=max(ans[1][i-1],ans[0][i-1]-prices[i]);
ans[2][i]=ans[1][i-1]+prices[i];
}
return max(ans[0][n-1],ans[2][n-1]);
}
};