Buy & Sell Stock II

PHOTO EMBED

Sun Jun 23 2024 12:22:13 GMT+0000 (Coordinated Universal Time)

Saved by @ayushg103 #c++

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

This is one of the recursions starting from 0 to N not N to 0 Some Notable Points 1) Here two there were four possibilities instead of two. Pick, Non Pick , Buy , Sell. See How buy/sell is coded. 2) Base Case was taken till n not n-1.(i.e Out of vector) hence returned 0; 3) f(ind) means Starting from index=ind what maximum profit you can make;