309. Best Time to Buy and Sell Stock with Cooldown

DP有點難。
看到一個不錯的講解,對應的轉移方程:

  • 在持有 buy[i] = max(sell[i-2] - price[i], buy[i-1])
  • 不在持有 sell[i] = max(buy[i-1] + price[i],sell[i-1])

代碼的話像覃超說的,轉移方程出來了就不要動腦子了。注意Java這邊不太好用-1做數(shù)組下標。

    public int maxProfit(int[] prices) {
        if (prices.length < 2) return 0;
        int[] buy = new int[prices.length];
        int[] sell = new int[prices.length];
        buy[0] = -prices[0];
        buy[1] = Math.max(-prices[0] , -prices[1]);
        sell[0] = 0;
        sell[1] = Math.max(prices[1] - prices[0] , 0 );
        for (int i = 2; i < prices.length; i++) {
            sell[i] = Math.max(buy[i - 1] + prices[i], sell[i - 1]);
            buy[i] = Math.max(sell[i - 2] - prices[i], buy[i - 1]);
        }
        return sell[sell.length - 1];
    }
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容