代码随想录算法训练营第四十八天| 121. 买卖股票的最佳时机、122.买卖股票的最佳时机II
121. 买卖股票的最佳时机
题目链接
文章讲解
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int dp[2] = {-prices[0], 0};
for (int i = 1; i < n; i++) {
int tmp1 = dp[0], tmp2 = dp[1];
dp[0] = max(tmp1, -prices[i]);
dp[1] = max(tmp1 + prices[i], tmp2);
}
return dp[1];
}
};
122.买卖股票的最佳时机II
题目链接
文章讲解
class Solution {
public:
int maxProfit(vector<int>& prices) {
int dp[2] = {-prices[0], 0};
for (int i = 1; i < prices.size(); i++) {
int tmp1 = dp[0], tmp2 = dp[1];
dp[0] = max(tmp1, tmp2 - prices[i]);
dp[1] = max(tmp2, tmp1 + prices[i]);
}
return dp[1];
}
};