You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
思路
这道题假如没有卖出时的手续费这个条件,那么其实是常见的动态规划+贪心问题,那么这道题多了一个手续费该如何处理呢?
其实,只需要把手续费当作是买入股票时的成本,在表示买入价格的dp数组中,把手续费也加进数组元素中就好啦。
状态转移方程
dp[i] = min(dp[i-1], prices[i] + fee)
边界条件
dp[0] = prices[0] + fee
代码
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int len = prices.size();
int dp[50005] = {0};
dp[0] = prices[0] + fee;
int sum = 0;
prices.push_back(0);
for(int i = 1; i < len; i++)
{
dp[i] = min(dp[i-1], prices[i] + fee);
if(prices[i] - dp[i-1] > 0 && prices[i] > prices[i+1])
{
sum += prices[i] - dp[i-1];
dp[i] = prices[i];
}
}
return sum;
}
};