Buy & Sell Stock III

PHOTO EMBED

Sun Jun 23 2024 13:02:41 GMT+0000 (Coordinated Universal Time)

Saved by @ayushg103 #c++

int f(int ind,int buy,int t, vector<int>& nums, vector<vector<vector<int>>>& dp)
{
    if(ind==(nums.size()) || t==0)
    return 0;
    if(dp[ind][buy][t]!=-1)
    return dp[ind][buy][t];
    int profit;
    if(buy && t)
    profit = max((-nums[ind]+f(ind+1,0,t,nums,dp)),(f(ind+1,1,t,nums,dp)));
    else
    profit = max((nums[ind]+f(ind+1,1,t-1,nums,dp)),(f(ind+1,0,t,nums,dp)));
    return dp[ind][buy][t]=profit;
}
    int maxProfit(vector<int>& prices) {
         int n = prices.size();
     vector<vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(3, -1)));


         return f(0,1,2,prices,dp);
        
    }
content_copyCOPY

Mistakes you did 1)you decreased t in buy . tmhe sell pe t decrease krna chahiye tha. Ek baar sochna ki kyu galat hua buy pe krne prr kyuki tmhra phla intuition to buy me decrease krna tha. You forgot t==0 in if(ind==(nums.size()) || t==0) This is how a 3D vector is initialized

Buy & Sell Stock II & III are important for Stock DP