https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
感觉跟https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
这个有点像 DP方程
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int dp[prices.size()+1][2];
for (int i = 0; i <= prices.size(); i++) {
dp[i][0] = dp[i][1] = INT_MIN/3;
}
dp[0][0] = 0;
int tmp;
// 1表示买 0表示卖
for (int i = 1; i <= prices.size(); i++) {
tmp = dp[i-1][1];
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i-1]);
dp[i][0] = max(dp[i-1][0], tmp - fee + prices[i-1]);
}
return dp[prices.size()][0];
}
};
参考了这个 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/126180/C++-DP-solution-summary
buy[i]表示,截止i天,最小的cost是多少,那么第i天,就有两种决策,一是不买入,二是买入
sell[i]表示,截止i天,最大的收益是多少,那么第i天,也有两种决策,一是不卖出,而是卖出
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
vector<int> buy(prices.size()+1, INT_MAX);
vector<int> sell(prices.size()+1, 0);
for(int i = 0; i < prices.size(); i++) {
buy[i + 1] = min( buy[i], prices[i] + fee - sell[i] );
sell[i+1] = max(sell[i], prices[i] - buy[i]);
}
return sell.back();
}
};