309. Best Time to Buy and Sell Stock with Cooldown

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]
// Dynamic Programming
int maxProfit(vector<int>& prices) { // time: O(n); space: O(n)
    int n = prices.size();
    if (n <= 1) return 0;
    vector<int> buy(n, numeric_limits<int>::min()), sell(n, 0);
    for (int i = 0; i < n; ++i) {
        buy[i] = max((i >= 1 ? buy[i - 1] : numeric_limits<int>::min()), (i >= 2 ? sell[i - 2] : 0) - prices[i]);
        sell[i] = max((i >= 1 ? sell[i - 1] : 0), (i >= 1 ? buy[i - 1] + prices[i] : 0));
        // cout << "buy[" << i << "] = " << buy[i] << ", sell[" << i << "] = " << sell[i] << endl; 
    }
    return sell.back();
}
int maxProfit(vector<int>& prices) { // time: O(n); space: O(1)
    int preBuy = numeric_limits<int>::min(), buy = numeric_limits<int>::min(), preSell = 0, sell = 0;
    for (int price : prices) {
        preBuy = buy;
        buy = max(buy, preSell - price);
        preSell = sell;
        sell = max(sell, preBuy + price);
        // cout << "buy = " << buy << ", sell = " << sell << endl;
    }
    return sell;
}
121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II123. Best Time to Buy and Sell Stock III188. Best Time to Buy and Sell Stock IV714. Best Time to Buy and Sell Stock with Transaction Fee

Last updated

Was this helpful?