BackendML

Best Time to Buy and Sell Stock with Cooldown

Medium3 min read
The Best Time to Buy and Sell Stock with Cooldown problem requires maximizing profit from stock transactions when a cooldown period is required after selling a stock.

Problem

Given an integer array prices, where prices[i] represents the stock price on the ith day, determine the maximum profit you can achieve.

You may buy and sell stocks multiple times, but after selling a stock, you must wait for one day before buying again. You can hold at most one stock at a time.

Example(s)

Example 1

Input
prices = [1,2,3,0,2]
Output
3

Example 2

Input
prices = [1]
Output
0

Solution

This problem can be solved using Dynamic Programming with Memoization. At each day, we track whether we currently hold a stock. Instead of storing only whether we can buy, we store the day on which the stock was bought.

We use stock to store the index of the day when the stock was bought. If stock = -1, we are not holding a stock, so we can either skip the current day or buy the stock on that day.

If stock >= 0, we are holding the stock bought on day stock. We can either sell it on the current day or continue holding it.

When we sell the stock on day i, we move to i + 2 because the next day is the cooldown day.

The state (i, stock) is stored in the memo array. Since stock can be -1, we use stock + 1 as the memoization index.
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;

        if (n == 0)
            return 0;

        Integer[][] memo = new Integer[n][n + 1];
        return maxProfit(prices, 0, -1, memo);
    }

    private int maxProfit(int[] prices, int i, int stock, Integer[][] memo) {
        if (i >= prices.length)
            return 0;

        if (memo[i][stock + 1] != null)
            return memo[i][stock + 1];

        if (stock == -1) {
            return memo[i][stock + 1] = Math.max(
                    maxProfit(prices, i + 1, stock, memo),
                    maxProfit(prices, i + 1, i, memo)
            );
        } else {
            return memo[i][stock + 1] = Math.max(
                    (prices[i] - prices[stock]) +
                            maxProfit(prices, i + 2, -1, memo),
                    maxProfit(prices, i + 1, stock, memo)
            );
        }
    }
}

Complexity

There are n × (n + 1) possible states because i can have n values and stock can represent any previous day or -1. Each state is calculated only once, so the time complexity is O(n²).

The memoization array stores O(n²) states, and the recursion stack can grow up to O(n). Therefore, the extra space complexity is O(n²).

Comments

No comments yet. Ask a question or share what helped.