Algorithm


Problem Name: 309. Best Time to Buy and Sell Stock with Cooldown

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

Code Examples

#1 Code Example with C Programming

Code - C Programming


int _max(int a, int b) {
    return a > b ? a : b;
}
int maxProfit(int* prices, int pricesSize) {
    int i;
    int buy_today, sell_today, cool_today;  // max profit of every possible status on a day
    int buy_yesterday, sell_yesterday, cool_yesterday;
    
    buy_today = 0 - prices[0];
    sell_today = cool_today = 0;
    
    for (i = 1; i  <  pricesSize; i ++) {
        buy_yesterday = buy_today;
        sell_yesterday = sell_today;
        cool_yesterday = cool_today;
        
        buy_today  = _max(buy_yesterday,  cool_yesterday - prices[i]);
        sell_today = _max(sell_yesterday, buy_yesterday + prices[i]);
        cool_today = _max(cool_yesterday, sell_yesterday);
    }
    
    return sell_today;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1,2,3,0,2]

Output

x
+
cmd
3

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n < 2) return 0;
        vector<int>buy(n), sell(n), rest(n);
        buy[0] = -prices[0];
        sell[0] = 0;
        rest[0] = 0;
        for(int i = 1; i  <  n; i++){
            buy[i] = max(buy[i - 1], rest[i - 1] - prices[i]);
            sell[i] = max(sell[i - 1], buy[i - 1] + prices[i]);
            rest[i] = max(rest[i - 1], sell[i - 1]);
        }
        return max(rest[n - 1], sell[n - 1]>;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1,2,3,0,2]

Output

x
+
cmd
3

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  int[] prices;
  Integer[] buyCache;
  Integer[] sellCache;
  public int maxProfit(int[] prices) {
    this.prices = prices;
    this.buyCache = new Integer[prices.length];
    this.sellCache = new Integer[prices.length];
    return buy(0);
  }
  
  private int buy(int idx) {
    if (idx >= prices.length) {
      return 0;
    }
    if (buyCache[idx] != null) {
      return buyCache[idx];
    }
    int cost = -prices[idx];
    int bestProfitBuying = sell(idx + 1) + cost;
    int bestProfitNotBuying = buy(idx + 1);
    buyCache[idx] = Math.max(bestProfitBuying, bestProfitNotBuying);
    return buyCache[idx];
  }
  
  private int sell(int idx) {
    if (idx == prices.length) {
      return 0;
    }
    if (sellCache[idx] != null) {
      return sellCache[idx];
    }
    int price = prices[idx];
    int bestProftSelling = buy(idx + 2) + price;
    int bestProfitNotSelling = sell(idx + 1);
    sellCache[idx] = Math.max(bestProftSelling, bestProfitNotSelling);
    return sellCache[idx];
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1]

#4 Code Example with Javascript Programming

Code - Javascript Programming


const maxProfit = function(prices) {
  if (prices === null || prices.length < 1) {
    return 0;
  }

  const length = prices.length;
  // buy[i]: max profit if the first "i" days end with a "buy" day
  const buy = Array(length + 1).fill(0); 
  // buy[i]: max profit if the first "i" days end with a "sell" day
  const sell = Array(length + 1).fill(0); 

  buy[1] = -prices[0];

  for (let i = 2; i  < = length; i++) {
    const price = prices[i - 1];
    buy[i] = Math.max(buy[i - 1], sell[i - 2] - price);
    sell[i] = Math.max(sell[i - 1], buy[i - 1] + price);
  }

  // sell[length] >= buy[length]
  return sell[length];
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1]

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def maxProfit(self, prices):
        dp1, dp2, dp3 = 0, 0, -float("inf")
        for p in prices:
            dp1, dp2, dp3 = dp3 + p, max(dp1, dp2), max(dp2 - p, dp3)
        return max(dp1, dp2)
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1,2,3,0,2]

Output

x
+
cmd
3

#6 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _0309_BestTimeToBuyAndSellStockWithCooldown
    {
        public int MaxProfit(int[] prices)
        {
            int sold = int.MinValue, held = int.MinValue, reset = 0;

            foreach (var price in prices)
            {
                var temp = sold;

                sold = held + price;
                held = Math.Max(held, reset - price);
                reset = Math.Max(reset, temp);
            }

            return Math.Max(sold, reset);
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
prices = [1,2,3,0,2]

Output

x
+
cmd
3
Advertisements

Demonstration


Previous
#307 Leetcode Range Sum Query - Mutable Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#310 Leetcode Minimum Height Trees Solution in C, C++, Java, JavaScript, Python, C# Leetcode