class Solution {
public:
int maxProfit(vector<int>& prices) {
int low = INT_MAX;
int result = 0;
for (int i = 0; i < prices.size(); i++) {
low = min(low, prices[i]); // 取最左最小价格
result = max(result, prices[i] - low); // 直接取最大区间利润
}
return result;
}
};
// 优化前
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
vector<int> dp(len);
int result = 0;
for(int i = 1; i < len; i++){
dp[i] = max(prices[i] - prices[i - 1], prices[i] - prices[i - 1] + dp[i - 1]);
result = max(result, dp[i]);
}
return result;
}
};
// 优化后
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
int dp0 = 0, dp1 = 0; // 只需要维护滚动两个值
int result = 0;
for(int i = 1; i < len; i++){
dp1 = max(prices[i] - prices[i - 1], prices[i] - prices[i - 1] + dp0);
result = max(result, dp1);
dp0 = dp1; // 互换
}
return result;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
vector<vector<int>> dp(len, vector<int>(2));
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 dp[len - 1][1];
}
};
先到这(饿了),看评论区尝试了一下一维和改进废了些时间,晚上有空继续刷股票