Best Time to Buy and Sell Stock with Cooldown - Medium - L - Star

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/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).

Approach

  • Variable iteration
  • https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323

Solution

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy0, buy1, sell0, sell1, sell2;
        int n = prices.size();
        if (n<2) {
            return 0;
        }
        buy0 = max(-prices[0], -prices[1]);
        buy1 = -prices[0];
        sell0 = max(0, buy1 + prices [1]);
        sell1 = sell0;
        sell2 = 0;
        buy1 = buy0;
        for(int i = 2; i<n; i++) {
            buy0 = max(buy1,  sell2 - prices[i]);
            sell0 = max(sell1, buy1 + prices[i]);
            sell2 = sell1;
            sell1 = sell0;
            buy1 = buy0;
        }
        return sell0;
    }
};