一、题目内容 中等

给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

示例1:

输入:prices = [1, 3, 2, 8, 4, 9], fee = 2 输出:8 解释:能够达到的最大利润:
在此处买入 prices[0] = 1 在此处卖出 prices[3] = 8 在此处买入 prices[4] = 4 在此处卖出 prices[5] = 9 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8

示例2:

输入:prices = [1,3,7,5,10,3], fee = 3 输出:6

提示:

  • 1 <= prices.length <= 5 * 104
  • 1 <= prices[i] < 5 * 104
  • 0 <= fee < 5 * 104

    二、解题思路

    买卖股票最佳时机,看的就是买入时机卖出时机
    我们举个例子:prices = [1, 4, 7], fee = 2

假如买入时机是看prices[i + 1] > prices[i] + fee,卖出时机是也是prices[i + 1] > prices[i] + fee,也就是说有赚一点就卖出。

  1. 第一步4 > 1 + 2买入,顺便卖出,赚了4 - 2 - 1 = 1
  2. 第二步7 > 4 + 2卖入,顺便卖出,赚了7 - 4 - 2 = 1

一共赚了 2 块。很明显不是最佳选择,我7 - 2 - 1 = 4不是更香吗。这个买入卖出时机废除。

刚才说到 7 - 2 - 1,也就是说有利润时,并不一定是卖出的最佳时机。
如果在 4 时卖出,如果要在 7 卖出,就得先买入 4,多花了一次手续费。我们要想办法把这次手续费去掉

  1. 4 - 2 - 1 = prices[1] - fee - prices[0] = profit1
  2. 7 - 2 - Math.min(4, 1) = 7 - 2 - Math.min(4, 4 - 2 -1) = prices[2] - fee - (prices[1] - fee - profit1)

这意味着,我们可以用 prices[i + 1] - fee - profit来表示,i 的 prices[i]

三、具体代码

  1. /**
  2. * @param {number[]} prices
  3. * @param {number} fee
  4. * @return {number}
  5. */
  6. var maxProfit = function (prices, fee) {
  7. let profit = 0
  8. let minPrice = Infinity
  9. for (let i = 0, len = prices.length; i < len; i++) {
  10. minPrice = Math.min(minPrice, prices[i])
  11. if (prices[i] - minPrice - fee > 0) {
  12. profit += prices[i] - minPrice - fee
  13. minPrice = prices[i] - fee
  14. }
  15. }
  16. return profit
  17. };

四、其他解法