Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

309. Best Time to Buy and Sell Stock with Cooldown

Explanation

To solve this problem, we can use dynamic programming with state machines. We can define three states: buy, sell, and cooldown. At each day, we can be in one of these states. We need to keep track of the maximum profit we can achieve at each state.

  • sell[i]: Maximum profit on day i if we sell on day i.
  • buy[i]: Maximum profit on day i if we buy on day i.
  • cooldown[i]: Maximum profit on day i if we are in cooldown on day i.

We can update these states based on the following conditions:

  • sell[i] = buy[i-1] + prices[i]
  • buy[i] = max(cooldown[i-1] - prices[i], buy[i-1])
  • cooldown[i] = max(sell[i-1], cooldown[i-1])

The final answer will be the maximum of sell[n-1] and cooldown[n-1], where n is the number of days.

Time complexity: O(n)
Space complexity: O(1)

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) {
            return 0;
        }
        
        int sell = 0, buy = -prices[0], cooldown = 0;
        
        for (int i = 1; i < prices.length; i++) {
            int prevSell = sell;
            sell = buy + prices[i];
            buy = Math.max(cooldown - prices[i], buy);
            cooldown = Math.max(prevSell, cooldown);
        }
        
        return Math.max(sell, cooldown);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.