Table of contents
LeeCode 123. Best Time to Buy and Sell Stocks III
LeeCode 188. Best Time to Buy and Sell Stocks IV
LeeCode 123. Best Time to Buy and Sell Stocks III
123. The Best Time to Buy and Sell Stocks III - LeetCode
Moving back to five parts :
1. Determine the meaning of the dp array and the subscript: 5 possible states in a day: 0. No operation; 1. Holding stocks for the first time; 2. Not holding stocks for the first time; 3. Holding stocks for the second time; 4. Do not hold stocks for the second time; in dp[i][j], i represents the i-th day, j represents the five states [0 - 4], and dp[i][j] represents the remaining state j of the i-th day maximum cash.
2.确定递推公式:dp[i][1] = max(dp[i-1][0] - prices[i], dp[i - 1][1]); dp[i][2] = max(dp[i - 1][1] + prices[i], dp[i - 1][2]); dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]); dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
3. How to initialize the dp array: dp[0][0] = 0; dp[0][1] = -prices[0]; dp[0][2] = 0; dp[0][3] = - prices[0]; dp[0][4] = 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) {
if (prices.size() == 0) return 0;
vector<vector<int>> dp(prices.size(), vector<int>(5, 0));
dp[0][1] = -prices[0];
dp[0][3] = -prices[0];
for (int i = 1; i < prices.size(); i++) {
dp[i][0] = dp[i - 1][0];
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
}
return dp[prices.size() - 1][4];
}
};
Time complexity: O(n) Space complexity: O(5n)
LeeCode 188. Best Time to Buy and Sell Stocks IV
188. The Best Time to Buy and Sell Stocks IV - LeetCode
Moving back to five parts :
1. Determine the meaning of the dp array and the subscript: define a two-dimensional dp array, dp[i][j]: the state of the i-th day is j, and the remaining maximum cash;
2. Determine the recursive formula:
for (int j = 0; j < 2 * k - 1; j += 2) {
dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]);
dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]);
}
3. How to initialize the dp array:
for (int j = 1; j < 2 * k; j += 2) {
dp[0][j] = -prices[0];
}
4. Determine the traversal order: traverse from front to back;
5. Example of recursive dp array;
code:
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if (prices.size() == 0) return 0;
vector<vector<int>> dp(prices.size(), vector<int>(2 * k + 1, 0));
for (int j = 1; j < 2 * k; j += 2) {
dp[0][j] = -prices[0];
}
for (int i = 1; i < prices.size(); i++) {
for (int j = 0; j < 2 * k - 1; j += 2) {
dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]);
dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]);
}
}
return dp[prices.size() - 1][2 * k];
}
};
Time complexity: O(n*k) Space complexity: O(n*k)