Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Best Time to Buy and Sell Stock with Cooldown 🌟🌟

UNLIMITED TRANSACTIONS WITH 1 DAY COOLDOWN

Tabulation from stock II

Code

int stockProfit(vector<int> &prices){
    int n = prices.size();
    vector<vector<int>> dp(n + 2, vector<int>(2, 0)); // n+2 instead of n+1
    dp[n][0] = dp[n][1] = 0;
    for (int ind = n - 1; ind >= 0; ind--) {
        for (int buy = 0; buy <= 1; buy++) {
            int profit = 0;
            if (buy) {
                int buyStock = -prices[ind] + dp[ind + 1][0];
                int dontBuyStock = dp[ind + 1][1];
                profit = max(buyStock, dontBuyStock);
            } else {
                int sellStock = dp[ind + 1][0];
                int dontSellStock = prices[ind] + dp[ind + 2][1]; // ind+2 instead of ind+1
                profit = max(sellStock, dontSellStock);
            }
            dp[ind][buy] = profit;
        }
    }
    return dp[0][1];
}

Removing redundant part

Code

int stockProfit(vector<int>& prices)
{
    int n = prices.size();
    vector<vector<int>> dp(n + 2, vector<int>(2, 0)); // n+2 instead of n+1

    for (int ind = n - 1; ind >= 0; ind--) {
        dp[ind][1] = max(-prices[ind] + dp[ind + 1][0], dp[ind + 1][1]);
        dp[ind][0] = max(prices[ind] + dp[ind + 2][1], dp[ind + 1][0]); // ind+2
    }
    return dp[0][1];
}

Space optimized tabulation

Code

int stockProfit(vector<int>& prices)
{
    int n = prices.size();
    vector<int> front2(2, 0);
    vector<int> front1(2, 0);
    vector<int> curr(2, 0);

    for (int ind = n - 1; ind >= 0; ind--) {
        curr[1] = max(-prices[ind] + front1[0], front1[1]);
        curr[0] = max(prices[ind] + front2[1], front1[0]);
        front2 = front1;
        front1 = curr;
    }
    return curr[1];
}

Other solutions