309. Best Time to Buy and Sell Stock with Cooldown

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

Problem

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]

Solution

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.size() < 2) return 0;
        const int n = prices.size();
        int buy[n], sell[n], cooldown[n];
        buy[0] = -prices[0]; // max profit after buy on i-th day
        sell[0] = 0;         // max profit after sell on i-th day
        cooldown[0] = 0;     // max profit after cooldown on i-th day
        int max_buy = buy[0];
        for (int i = 1; i < prices.size(); ++i) {
            buy[i] = cooldown[i - 1] - prices[i];
            sell[i] = max_buy + prices[i];
            cooldown[i] = max(buy[i - 1], max(sell[i - 1], cooldown[i - 1]));
            max_buy = max(max_buy, buy[i]);
        }
        return max(buy[n - 1], max(sell[n - 1], cooldown[n - 1]));
    }
};
  • #dp

Last updated

Was this helpful?