In this post, we are going to solve the 309. Best Time to Buy and Sell Stock with Cooldown problem of Leetcode. This problem 309. Best Time to Buy and Sell Stock with Cooldown is a Leetcode medium level problem. Let’s see code, 309. Best Time to Buy and Sell Stock with Cooldown – Leetcode Solution.
Problem
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).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1 :
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Example 2 :
Input: prices = [1]
Output: 0
Constraints
1 <= prices.length <= 5000
0 <= prices[i] <= 1000
Now, let’s see the code of 309. Best Time to Buy and Sell Stock with Cooldown – Leetcode Solution.
Best Time to Buy and Sell Stock with Cooldown – Leetcode Solution
309. Best Time to Buy and Sell Stock with Cooldown – Solution in Java
class Solution { public int maxProfit(int[] prices) { int obsp = -prices[0]; int ossp = 0; int ocsp = 0; for(int i=1;i<prices.length;i++){ int nbsp = 0; int nssp = 0; int ncsp = 0; if(ocsp - prices[i] > obsp){ nbsp = ocsp - prices[i]; }else{ nbsp = obsp; } if(obsp + prices[i] > ossp){ nssp = obsp + prices[i]; }else{ nssp = ossp; } if(ossp > ocsp){ ncsp = ossp; }else{ ncsp = ocsp; } obsp = nbsp; ossp = nssp; ocsp = ncsp; } return Math.max(obsp,Math.max(ossp,ocsp)); } }
309. Best Time to Buy and Sell Stock with Cooldown – Solution in C++
class Solution { public: int maxProfit(vector<int>& prices) { int obsp = -prices[0]; int ossp = 0; int ocsp = 0; for(int i=1;i<prices.size();i++){ int nbsp = 0; int nssp = 0; int ncsp = 0; if(ocsp - prices[i] > obsp){ nbsp = ocsp - prices[i]; }else{ nbsp = obsp; } if(obsp + prices[i] > ossp){ nssp = obsp + prices[i]; }else{ nssp = ossp; } if(ossp > ocsp){ ncsp = ossp; }else{ ncsp = ocsp; } obsp = nbsp; ossp = nssp; ocsp = ncsp; } return max(obsp,max(ossp,ocsp)); } };
309. Best Time to Buy and Sell Stock with Cooldown – Solution in Python
class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices)==1: return 0 dpb0=-prices[0] dps0=0 dpb1=-min(prices[0],prices[1]) dps1=max(dps0,dpb0+prices[1]) for i in range(2,len(prices)): temp=max(dpb1,dps0-prices[i]) temp2=max(dps1,dpb1+prices[i]) dpb0=dpb1 dps0=dps1 dpb1=temp dps1=temp2 return dps1 if dps1>0 else 0
Note: This problem 309. Best Time to Buy and Sell Stock with Cooldown is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.