class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()){
return 0;
}
int n = prices.size();
int f0 = -prices[0], f1 = 0, f2 = 0;
for (int i = 1; i < n; i ++ ){
int g0 = max(f0, f2 - prices[i]);
int g1 = f0 + prices[i];
int g2 = max(f1, f2);
f0 = g0;
f1 = g1;
f2 = g2;
}
return max(f1, f2);
}
};
买卖股票的最佳时机含手续费
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
int f0 = -prices[0];
int f1 = 0;
for (int i = 1; i < n; i ++ ){
int g0 = max(f0, f1 - prices[i]);
int g1 = max(f1, f0 + prices[i] - fee);
f0 = g0;
f1 = g1;
}
return f1;
}
};
|