Description Link to heading

309.best-time-to-buy-and-sell-stock-with-cooldown

Solution Link to heading

The key point is find what dp should denote and its recurrence formula.

dp[i] indicates only considering first i days, and is devided into five cases: no operation, bought but not sold (stock in hand), exactly sold, cooling off period, and idle, which are noted as dp[i][0], dp[i][1], dp[i][2], dp[i][3], and dp[i][4] correspondingly.

Recurrence formula:

  • dp[i][0] = dp[i - 1][0];
  • dp[i][1] = max4(dp[i - 1][1], dp[i - 1][0] - prices[i - 1], dp[i - 1][4] - prices[i - 1], dp[i - 1][3] - prices[i - 1]); // last day can be on operation, bought but not sold, cooling off period, idle
  • dp[i][2] = dp[i - 1][1] + prices[i - 1];
  • dp[i][3] = dp[i - 1][2];
  • dp[i][4] = max(dp[i - 1][3], dp[i - 1][4]); // last day can be cooling off period adn idle.

Code Link to heading

#include <vector>
using std::vector;
class Solution {
  private:
    int max3(int a, int b, int c) {
        if (a > b)
            return a > c ? a : c;
        else
            return b > c ? b : c;
    }
    int max4(int a, int b, int c, int d) {
        int l = a > b ? a : b;
        int r = c > d ? c : d;
        return l > r ? l : r;
    }

  public:
    int maxProfit(vector<int> &prices) {
        vector<vector<int>> dp(prices.size() + 1, vector<int>(5, 0));
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        dp[0][2] = 0;
        dp[0][3] = 0;
        dp[0][4] = 0;
        for (int i = 1; i <= prices.size(); i++) {
            dp[i][0] = dp[i - 1][0];
            dp[i][1] = max4(dp[i - 1][1], dp[i - 1][0] - prices[i - 1], dp[i - 1][4] - prices[i - 1], dp[i - 1][3] - prices[i - 1]);
            dp[i][2] = dp[i - 1][1] + prices[i - 1];
            dp[i][3] = dp[i - 1][2];
            dp[i][4] = max(dp[i - 1][3], dp[i - 1][4]);
        }
        return max3(dp[prices.size()][2], dp[prices.size()][3], dp[prices.size()][4]);
    }
};