Here, We see Best Time to Buy and Sell Stock with Cooldown LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
![Best Time to Buy and Sell Stock with Cooldown LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Best Time to Buy and Sell Stock with Cooldown LeetCode Solution
Table of Contents
Problem Statement
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
Best Time to Buy and Sell Stock with Cooldown LeetCode Solution C++
class Solution {
public:
int maxProfit(vector<int> &prices) {
int buy(INT_MIN), sell(0), prev_sell(0), prev_buy;
for (int price : prices) {
prev_buy = buy;
buy = max(prev_sell - price, buy);
prev_sell = sell;
sell = max(prev_buy + price, sell);
}
return sell;
}
};
Code language: PHP (php)
Best Time to Buy and Sell Stock with Cooldown LeetCode Solution Java
class Solution {
public int maxProfit(int[] prices) {
int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy;
for (int price : prices) {
prev_buy = buy;
buy = Math.max(prev_sell - price, prev_buy);
prev_sell = sell;
sell = Math.max(prev_buy + price, prev_sell);
}
return sell;
}
}
Code language: JavaScript (javascript)
Best Time to Buy and Sell Stock with Cooldown Solution JavaScript
var maxProfit = function(prices) {
let [coolDown, sell, hold] = [0, 0, Number.NEGATIVE_INFINITY];
for( let stockPrice_Day_i of prices){
let [prevCoolDown, prevSell, prevHold] = [coolDown, sell, hold];
coolDown = Math.max(prevCoolDown, prevSell);
sell = prevHold + stockPrice_Day_i;
hold = Math.max( prevHold, prevCoolDown - stockPrice_Day_i );
}
return Math.max(sell, coolDown);
};
Code language: JavaScript (javascript)
Best Time to Buy and Sell Stock with Cooldown Solution Python
class Solution(object):
def maxProfit(self, prices):
if len(prices) < 2:
return 0
sell, buy, prev_sell, prev_buy = 0, -prices[0], 0, 0
for price in prices:
prev_buy = buy
buy = max(prev_sell - price, prev_buy)
prev_sell = sell
sell = max(prev_buy + price, prev_sell)
return sell
Code language: HTML, XML (xml)