309. Best Time to Buy and Sell Stock with Cooldown

;  |     Back to Homepage   |     Back to Code List


class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        if (n == 0) return 0;
        
        int withShare = -prices[0];
        int cooldown = 0;
        int noShare = 0;
        for (int i = 1; i < n; i++) {
            withShare = Math.max(withShare, cooldown - prices[i]);
            cooldown = Math.max(cooldown, noShare);
            noShare = Math.max(noShare, withShare + prices[i]);
        }
        
        return noShare;
    }
}