class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> dp(prices.size(), 0);
int buyPrice = prices[0];
for (int i = 1; i < prices.size(); i ++) {
dp[i] = dp[i-1];
if (prices[i] > buyPrice) {
dp[i] += prices[i] - buyPrice;
}
buyPrice = prices[i];
}
return dp.back();
}
};
标准dp写法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> dp(2, 0);
dp[0] = - prices[0];
for (int i = 1; i < prices.size(); i ++) {
dp[0] = max(dp[1] - prices[i], dp[0]);
dp[1] = max(dp[1], dp[0] + prices[i]);
}
return dp[1];
}
};