本文最后更新于:2022年4月9日 中午
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
| 输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
|
Solution
参考 @LeetCode官方
难点:定义状态,改变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int n = prices.size();
vector<vector<int>>f(n, vector<int>(3)); f[0][0] = -prices[0]; for(int i=1; i<n; ++i){ f[i][0] = max(f[i-1][0], f[i-1][2]-prices[i]); f[i][1] = f[i-1][0] + prices[i]; f[i][2] = max(f[i-1][1], f[i-1][2]); } return max(f[n-1][1], f[n-1][2]); } };
|
参考 迷途剑客
考虑四种状态的转移图:

- dp[i] [0]代表该天不持有股票且非卖出的最大利润
dp[i] [0] = Math.max(dp[i - 1] [0], dp[i - 1] [2]);
- dp[i] [1] 代表该天卖出股票的最大利润
dp[i] [1] = dp[i - 1] [3] + prices[i];
- dp[i] [2] 代表该天位冷冻期最大利润
dp[i] [2] = dp[i - 1] [1];
- dp[i] [3] 代表该天卖出股票的最大利润
dp[i] [3] = Math.max(dp[i - 1] [3], dp[i - 1] [0] - prices[i], dp[i-1] [2] - prices[i]);
初始:
- 不持股,非卖出 dp[0] [0] = 0;
- 卖出 dp[0] [1] = 0;
- 冷冻 dp[0] [2] = 0;
- 持股 dp[0] [3] = 0 - prices[0];
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int n = prices.size();
vector<vector<int>> f(n, vector<int>(4)); f[0][3] = -prices[0]; for(int i=1; i<n; ++i){ f[i][0] = max(f[i-1][0], f[i-1][2]); f[i][1] = f[i-1][3] + prices[i]; f[i][2] = f[i-1][1]; f[i][3] = max(f[i-1][3], max(f[i-1][0]-prices[i], f[i-1][2]-prices[i])); } return max(f[n-1][0], max(f[n-1][1], f[n-1][2])); } };
|