classSolution { public: constint inf = 0x3f3f3f3f; int dp[100010][3][2];
intmaxProfit(vector<int>& prices){ //状态机dp //阶段----当前是第i天,也就是时间。 //状态:剩余交易次数、股票持有状态下的股票收益 //决策:卖出股票、啥也不做、买入股票 int n = prices.size(); int k = 2; //base for (int k = 0; k <= 2; k++) { dp[0][k][0] = 0; dp[0][k][1] = -inf; }
for (int i = 0; i <= n; ++i) { dp[i][0][0] = 0; dp[i][0][1] = -inf; } for (int i = 1; i <= n; ++i) { for (int k = 1; k <= 2; k++) { //前一天没有股票;昨天有股票,今天卖出; dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i - 1]); //前一天有股票;昨天没有股票,今天买入 dp[i][k][1] = max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i - 1]); } }