Leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee (dp)
The solutions of the series of Best Time to Buy and Sell Stock are nearly the same by simply using dynamic programming. Just with some modifying.
Status
In this problem, we can use \(d[i][0]\) and \(d[i][1]\) to show that: in \(day_i\), with or without stock in my hands, the max money I can get.
Transfer expression
- \(d[i][0] = max(d[i - 1][0], d[i - 1][1] + a[i] - fee)\)
- \(d[i][1] = max(d[i - 1][1], d[i - 1][0] - a[i])\)
Analysis
From the expression we can know that:
- Status: \(O(n)\)
- Transfer: \(O(1)\)
So the time complexity is \(O(n)\) and space complexity is \(O(n)\).
Optimization
From the above expression, we can see that the space can be optimized. We only need the array d[2][2] with rolling.
Code
So the code is below:
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
const int n = prices.size();
int d[2][2] = {0};
// Init start info
d[0][1] = -prices[0];
int ans = 0;
// Roll
for (int i = 1, t = 1; i < n; ++i, t ^= 1) {
d[t][0] = max(d[t ^ 1][0], d[t ^ 1][1] + prices[i] - fee);
d[t][1] = max(d[t ^ 1][0] - prices[i], d[t ^ 1][1]);
ans = max(ans, max(d[t][0], d[t][1]));
}
return ans;
}
};

浙公网安备 33010602011771号