Table of contents
LeeCode 309. The best time to buy and sell stocks includes a freezing period
LeeCode 714. The best time to buy and sell stocks includes handling fees
LeeCode 309. The best time to buy and sell stocks includes a freezing period
309. The best time to buy and sell stocks includes a freezing period - LeetCode
Moving back to five parts:
1. Determine the meaning of the dp array and the subscript: dp[i][j], the status on the i-th day is j, and the remaining cash is the most. State 1: Holding stocks (buy stocks today, or hold stocks without any operation after buying stocks before); State 2: Keep selling stocks (the freezing period has passed); State 3: Sell today Stock out; State 4: Frozen state;
2.确定递推公式:dp[i][0] = max(dp[i - 1][0], dp[i - 1][3] - prices[i], dp[i - 1][1] - prices[i]); dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]); dp[i][2] = dp[i - 1][0] + prices[i]; dp[i][3] = dp[i - 1][2];
3. How to initialize the dp array: dp[0][0] = -prices[0]; dp[0][1] = 0; dp[0][2] = 0; dp[0][3] = 0 ;
4. Determine the traversal order: traverse from front to back;
5. Example of recursive dp array;
code :
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0;
vector<vector<int>> dp(n, vector<int>(4, 0));
dp[0][0] -= prices[0];
for (int i = 1; i < n; i ++) {
dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3] - prices[i], dp[i - 1][1] - prices[i]));
dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);
dp[i][2] = dp[i - 1][0] + prices[i];
dp[i][3] = dp[i - 1][2];
}
return max(dp[n - 1][3], max(dp[n - 1][1], dp[n - 1][2]));
}
};
Time complexity: O(n) Space complexity: O(n)
LeeCode 714. The best time to buy and sell stocks includes handling fees
714. The best time to buy and sell stocks includes handling fees - LeetCode
Greedy Algorithm
code:
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int result = 0;
int minPrice = prices[0]; //记录最低价格
for (int i = 1; i < prices.size(); i++) {
//买入
if (prices[i] < minPrice) minPrice = prices[i];
//保持原有状态
if (prices[i] >= minPrice && prices[i] <= minPrice + fee) continue;
//计算利润
if (prices[i] > minPrice + fee) {
result += prices[i] - minPrice - fee;
minPrice = prices[i] - fee; //避免重复扣手续费
}
}
return result;
}
};
Time complexity: O(n) Space complexity: O(1)
dynamic programming
Ideas:
The problem-solving steps are basically the same as those in 122. The best time to buy and sell stocks II. The difference is that the handling fee needs to be considered in the recursive formula.
递推公式:dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
code :
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] -= prices[0];
for (int i = 1; i < n; i++) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
return max(dp[n - 1][0], dp[n - 1][1]);
}
};
Time complexity: O(n) Space complexity: O(n)