You are given an array prices where prices[i] is the price of a given stock on the i-th 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).
- The transaction fee is only charged once for each stock purchase and sale.
Example 1:
Input: prices = [7,1,5,3,6,4], fee = 1
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5 - 1 - 1 = 3.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6 - 3 - 1 = 2.
Total profit is 3 + 2 = 5.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
Explanation: The total profit is (10 - 1) - 3 = 6.
Example 3:
Input: prices = [9,1,3,5,5,4,3,7,6,10,3,2,18], fee = 3
Output: 19
这道题是经典的“带手续费股票交易”动态规划问题:给定每日股价和每次交易手续费,要求在不能同时持有多笔仓位的前提下,计算最大利润。常见做法是用两个状态来维护——持有股票时的最大收益和不持有股票时的最大收益;每天根据“买入 / 卖出 / 不操作”进行状态转移,并在卖出或买入时正确扣除手续费。这样可以在线性时间内完成求解,适合处理题目中的多组示例和较长价格序列。