In this Leetcode Best Time to Buy and Sell Stock with Cooldown problem solution You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Leetcode Best Time to Buy and Sell Stock with Cooldown problem solution


Problem solution in Python.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) < 2:
            return 0
        dp = [[0 for x in range(2)] for i in range(len(prices))]
        prevdiff = -prices[0]
        
        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i-1][1], dp[i-1][0])
            if i-2 >= 0:
                prevdiff = max(prevdiff, dp[i-2][0] - prices[i-1])
            dp[i][1] = max(dp[i][1], prices[i] + prevdiff)
            
        return max(dp[len(prices)-1])



Problem solution in Java.

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if(n <2) return 0;
        int s0 = 0;
        int b1 = Math.max(-prices[0], -prices[1]);
        int s1 = Math.max(0, prices[1]- prices[0]);
        for(int i = 2; i< n; i++) {
            int b = Math.max(b1, s0 - prices[i]);
            int s = Math.max(s1, b1 + prices[i]);
            s0 = s1; b1 = b; s1 =s;
        }
        return s1;

    }
}


Problem solution in C++.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp(n,vector<int>(3,0)); 
        
        dp[0][0] = -prices[0];
        
        for(int i=1;i<n;++i)
        {
            dp[i][0] = max(dp[i-1][0],dp[i-1][2] - prices[i]) ;
            dp[i][1] = max(dp[i-1][0] + prices[i],dp[i-1][1]);
            dp[i][2] = max({dp[i-1][0],dp[i-1][1],dp[i-1][2]});
        } 
        return max({dp[n-1][0],dp[n-1][1],dp[n-1][2]});
    }
};


Problem solution in C.

int maxProfit(int* arr, int pricesSize){
   int obsp=-arr[0];
    int ossp=0;
    int ocsp=0;
    
    for(int i=1;i<pricesSize;i++){
        int nbsp=0, nssp=0, ncsp=0;
        
        if(ocsp - arr[i] > obsp)
            nbsp = ocsp - arr[i];
        else
            nbsp = obsp;
        
        if(obsp + arr[i] > ossp)
            nssp = obsp + arr[i];
        else
            nssp = ossp;
        
        if(ossp > ocsp)
            ncsp = ossp;
        else
            ncsp = ocsp;
     
        obsp = nbsp;
        ossp = nssp;
        ocsp = ncsp;    
    }
    
    return ossp;
}