Best time to buy and sell stocks
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
dp[i] represents the maximum profit that can be obtained by selling/not selling stocks on the i-th day:
1. Selling stocks: dp[i] = prices[i] -minPrice (the lowest price before i day)
2. Not selling stocks: dp[i] = dp[i-1] (because the stocks are not being sold, the status remains the same as the previous day)
∴dp[i] = max(dp[i-1], prices[i] - minPrice);
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n < 2) return 0;
vector<int> dp(n, 0);// dp[i] 表示在第i天结束时的最大利润
int minPrice = prices[0];
for (int i = 1; i < n; i++) {
if (prices[i] < minPrice) minPrice = prices[i];
dp[i]= max(dp[i-1],prices[i] - minPrice);
}
return dp.back();
}
};
The best time to buy and sell stocks II
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/Similar
to tree-shaped dp, an additional vector is added to store the current state: dp[i][0] means not held For stocks, dp[i][1] means holding stocks. Each state is transferred from the two states dp[i-1][0] and dp[i-1][1], so dp[i][0] = max(dp[i-1][0 ], dp[i-1][1] + prices[i]): The meaning is that there are no stocks on the i-th day, which may be because there are no stocks on i-1 day, or there are stocks on i-1 day but the i-th day If you sell it, the profit will be the same if there is no stock in the first place. If you sell the stock, you need to add the profit increased by selling the stock to the profit of dp[i-1][1]; dp[i]
[ 1] = max(dp[i-1][1], dp[i-1][0] - prices[i]) Similarly, it’s just that one receives money and the other spends it.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<vector<int>> dp (n, vector<int> (2, 0));
dp[0][1] = -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]);
}
return max(dp.back()[0], dp.back()[1]);
}
};