Shu-How Zの小窝

Loading...

188. 买卖股票的最佳时机 IV

  1. 买卖股票的最佳时机 IV

类比j为奇数是买,偶数是卖的状态

/**
 * @param {number[]} prices
 * @return {number}
 */
​    dp[0]: 无操作; 

​    dp[1]: 第一次买入;

​    dp[2]: 第一次卖出;

​    dp[3]: 第二次买入;

​    dp[4]: 第二次卖出;
	// 2*k+1 
var maxProfit = function(k, prices) {
    if(prices == null || prices.length < 2 || k == 0) return 0;
    let init=null
    const dp=new Array(2*k+1).fill(null)
    for(let i=1;i<=2*k;i+=2){
        dp[i]=-prices[0]
    }
    for(let i=1;i<prices.length;i++){
       for(let j=1;j<dp.length;j++){
           if(j%2) dp[j]=Math.max(dp[j],dp[j-1]-prices[i])
           else dp[j]=Math.max(dp[j],dp[j-1]+prices[i])
       }
    }
    return dp[2*k]
};  
// let prices = [3,3,5,0,0,3,1,4]
let k = 2, prices = [2,4,1]
console.log(maxProfit(k,prices))

…vjx

posted @ 2025-01-19 17:48  KooTeam  阅读(13)  评论(0)    收藏  举报