Featured image of post 309. 最佳买卖股票时机含冷冻期

309. 最佳买卖股票时机含冷冻期

题目描述

给定一个整数数组prices,其中第  prices[i] 表示第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

  • 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

  • 输入: prices = [1,2,3,0,2]
  • 输出: 3
  • 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

示例 2:

  • 输入: prices = [1]
  • 输出: 0

提示:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

解法一:动态规划

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

func maxProfit(prices []int) int {
    n := len(prices)
    dp := make([][3]int, n)
    // dp[i][0]:第 i 天结束后持有股票时获得的最大利润
    dp[0][0] = -prices[0]
    // dp[i][1]:第 i 天结束后未持有股票且未处于冻结期时获得的最大利润
    dp[0][1] = 0
    // dp[i][2]:第 i 天结束后未持有股票且处于冻结期时获得的最大利润
    dp[0][2] = 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][2])
        dp[i][2] = dp[i-1][0] + prices[i]
    }
    return max(dp[n-1][1], dp[n-1][2])
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/12 09:29:11
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计