309. Best Time to Buy and Sell Stock with Cooldown

自己的想法。雖然是O(n),但是感覺肯定是麻煩了。
習慣把所有stock問題都用同一種模板了。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1)    return 0;
        int n = prices.length;
        int dp[] = new int[n];
        dp[0] = 0;
        dp[1] = prices[1]-prices[0]>0? prices[1]-prices[0]:0;
        int max_tmp = prices[0] > prices[1] ? -prices[1]:-prices[0];
        
        for (int i=2; i<n; i++) {
            dp[i] = Math.max(max_tmp+prices[i], dp[i-1]);
            max_tmp = Math.max(max_tmp, dp[i-2]-prices[i]);
        }
        return dp[n-1];
    }
}

更好的,更簡單的解法。空間O(1)

public class Solution {
    public int maxProfit(int[] prices) {
        int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy;
        for(int price : prices) {
            prev_buy = buy;
            buy = Math.max(prev_sell - price, prev_buy);
            prev_sell = sell;
            sell = Math.max (prev_buy + price, prev_sell);
        }
        return sell;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容