问题描述
解题思路
本题的关键在于找到dp
的实际含义,以及它的递推关系;
dp[i]
表示只考虑前i
天的情况,分为无操作、买入未卖出(手中有股票)、正好卖出、冷静期、空闲五种情况,分别记为dp[i][0], dp[i][1], dp[i][2], dp[i][3], dp[i][4]
.
递推关系如下:
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]);
// 上一天可能有冷静期和空闲两种情况
代码
#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]);
}
};
标签:sell,309,buy,return,int,vector,prices,dp
From: https://www.cnblogs.com/zwyyy456/p/16792269.html