#include<vector> #include<algorithm> using std::vector;
classSolution { public: intmaxProfit(vector<int> &prices) { int i, n = prices.size(); int max_profit = 0;
if (n == 1) { return0; } // dp[i][j] represents the maximum profit up to day i in state j // dp[i][0] means no purchase, // dp[i][1] means first buy completed, // dp[i][2] means first sell completed, // dp[i][3] means second buy completed, // dp[i][4] means second sell completed vector<vector<int> > dp(n, vector<int>(5, 0)); dp[0][0] = 0; dp[0][1] = -prices[0]; dp[0][2] = -1e9; dp[0][3] = -1e9; dp[0][4] = -1e9;
// Each day you can choose not to buy, buy, or sell (only if you have already bought) for (i = 1; i < n; i++) { // The previous state of not buying is not buying dp[i][0] = dp[i - 1][0];
// The previous state of the first buy is not buying, either continue yesterday's state or buy today's stock dp[i][1] = std::max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
// The previous state of the first sell is the first buy, either continue yesterday's state or sell today's stock dp[i][2] = std::max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
// The previous state of the second buy is the first sell, either continue yesterday's state or buy today's stock dp[i][3] = std::max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
// The previous state of the second sell is the second buy, either continue yesterday's state or sell today's stock dp[i][4] = std::max(dp[i - 1][4], dp[i - 1][3] + prices[i]);