Featured image of post 714. 买卖股票的最佳时机含手续费

714. 买卖股票的最佳时机含手续费

题目描述

给定一个整数数组 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

解法一:动态规划

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func max(nums ...int) int {
    res := nums[0]
    for _, val := range nums {
        if val > res {
            res = val
        }
    }
    return res
}

func maxProfit(prices []int, fee int) int {
    n := len(prices)
    dp := make([][2]int, n)
    // dp[i][0] 记录在区间 prices[0...i] 进行交易,最后手持股票所能获得的最大利润
    dp[0][0] = -prices[0]
    // dp[i][1] 记录在区间 prices[0...i] 进行交易,最后没有股票所能获得的最大利润
    dp[0][1] = 0
    for i := 1; i < n; i++ {
        dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i])
        dp[i][1] = max(dp[i-1][1], dp[i-1][0]+prices[i]-fee)
    }
    // return dp[n-1][1] // correct
    return max(dp[n-1][0], dp[n-1][1])
}

官方题解如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func maxProfit(prices []int, fee int) int {
    n := len(prices)
    sell, buy := 0, -prices[0]
    for i := 1; i < n; i++ {
        sell = max(sell, buy+prices[i]-fee)
        buy = max(buy, sell-prices[i])
    }
    return sell
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

贪心

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func maxProfit(prices []int, fee int) int {
    buy := math.MaxInt32
    profit := 0
    for i := 0; i < len(prices); i++ {
        if prices[i]+fee < buy {
            buy = prices[i] + fee
        } else if prices[i] > buy {
            profit += prices[i] - buy
            buy = prices[i]
        }
    }
    return profit
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/12 11:28:44
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计