Skip to content
On this page

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

TIP

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

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

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

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

思路

  • 买入所以持有
  • 没有买入但还是持有
  • 卖出所以不持有
  • 没有卖出但还是不持有
js
var maxProfit = function(prices) {
    let dp =  Array(prices.length).fill().map(() => Array(4).fill(0))
    dp[0][0] -= prices[0]   //买入所以持有
    dp[0][1] -= prices[0]   //没有买入但还是持有
    dp[0][2] = 0            //卖出所以不持有
    dp[0][3] = 0            //没有卖出但还是不持有
    for(let i=1;i<prices.length;i++){
        dp[i][0] = dp[i-1][3]-prices[i] 
        dp[i][1] = Math.max(dp[i-1][0],dp[i-1][1])
        dp[i][2] = Math.max(dp[i-1][0]+prices[i],dp[i-1][1]+prices[i])
        dp[i][3] = Math.max(dp[i-1][2],dp[i-1][3])
    }
    console.log(dp)
    return Math.max(dp[prices.length-1][2],dp[prices.length-1][3]) 
};