题目:
状态转移,注意初始化不要用 INT_MIN,会导致后面计算溢出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <vector> #include <algorithm> using std::vector;
class Solution { public: int maxProfit(vector<int> &prices) { int i, n = prices.size(); int max_profit = 0;
if (n == 1) { return 0; } 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;
for (i = 1; i < n; i++) { dp[i][0] = dp[i - 1][0];
dp[i][1] = std::max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = std::max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = std::max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = std::max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
max_profit = std::max({ dp[i][0], dp[i][2], dp[i][4], max_profit }); } return max_profit; } };
|