买卖股票的最佳时机
力扣题目链接
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
vector<vector<int>> dp(len, vector<int>(2,0));
dp[0][0] = -prices[0];
for(int i = 1; i < len; i++){
dp[i][0] = max(dp[i-1][0], -prices[i]);
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i]);
}
return max(dp[len-1][1], 0);
}
};
买卖股票的最佳时机II
力扣题目链接
class Solution {
public:
int maxProfit(vector<int>& prices) {
// dp[i][0]持有股票,dp[i][1]不持有股票
vector<vector<int>> dp(prices.size(), vector<int>(2,0));
dp[0][0] = -prices[0];
for(int i = 1; i < prices.size(); i++){
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i]);
dp[i][1] = max(dp[i-1][0] + prices[i], dp[i-1][1]);
}
return dp[prices.size()-1][1];
}
};
买卖股票的最佳时机III
力扣题目链接
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(4,0));
dp[0][0] = -prices[0];
dp[0][2] = -prices[0];
for(int i = 1; i < n; i++){
dp[i][0] = max(dp[i-1][0], -prices[i]);
dp[i][1] = max(dp[i-1][1], dp[i][0] + prices[i]);
dp[i][2] = max(dp[i-1][2], dp[i][1]-prices[i]);
dp[i][3] = max(dp[i-1][3], dp[i][2] + prices[i]);
}
return max(dp[n-1][1], dp[n-1][3]);
}
};