Best Time to Buy and Sell Stock with Cooldown

Find the most profit from buying and selling a stock when every sale is followed by a day of waiting.

Given an array prices, where prices[i] is the price of one share of a stock on day i, return the most profit you can make. You may buy and sell as many times as you like, but you can hold at most one share, so you must sell it before buying again. After a sale you must wait one full day, called the cooldown, before you buy again. Prices are zero or more.

Example 1
Input: prices = [1, 2, 3, 0, 2]
Output: 3
Explanation: buy on day 0 at 1, sell on day 1 at 2, wait on day 2, buy on day 3 at 0, sell on day 4 at 2.
Example 2
Input: prices = [1]
Output: 0
Explanation: with a single day there is no later day to sell on.
Solution

The Idea

Imagine you follow the price of one share for five days: 1, 2, 3, 0 and 2. Each day you may buy the share, sell it if you have it, or do nothing. Your profit is what you sold for minus what you paid. The twist is the rule after a sale: on the day after selling, you may not buy.

Without that rule the best plan is easy to spot: buy at 1, sell at 3 on day 2, buy at 0 on day 3 and sell at 2 on day 4, for 2 + 2 = 4. But day 3 comes right after the sale on day 2, so that purchase is not allowed. Selling at 3 and then waiting leaves only day 4, which earns nothing, so that plan stops at 2.

Selling one day earlier, at 2, gives up 1 of profit on the first trade. In return, day 2 becomes the cooldown and day 3 is free for buying at 0. That plan earns 1 + 2 = 3, the answer to Example 1.

So a choice made today changes what is allowed tomorrow. How can we choose well each day without knowing the prices to come? Notice that tomorrow's options depend only on how today ended. At the end of any day you are in one of three situations: you are holding a share, you sold today, or you hold nothing and are free to buy.

For each situation it is enough to remember the best cash you could have when ending the day in it. Cash starts at 0, a purchase subtracts the price and a sale adds it, so cash drops below 0 while you hold a share you paid for. Look at the picture below.

Three situations at the end of a day: free to buy, holding a share and sold today. Buying leads from free to buy to holding a share, selling leads to sold today, and after one day of cooldown a sale leads back to free to buy. Below, a table of the best cash in each situation for prices 1, 2, 3, 0, 2. Sold today on day 4 is 3, the answer.

The top part shows how the three situations connect. From free to buy, buying leads to holding a share, and from holding a share, selling leads to sold today. Sold today has a single arrow out: after one day of cooldown you are free to buy again. The small loops are days on which you do nothing.

The table below it holds the best cash for Example 1, one column per day. On day 1, the share bought at 1 is sold at 2, so the row labelled sold today shows 1. Day 2 is the cooldown after that sale, so at its end the row labelled free to buy shows 1.

On day 3, buying at 0 with that 1 makes holding a share 1. On day 4, selling at 2 makes sold today 3, the answer. The dash on day 0 means no sale is possible yet, because nothing was bought before day 0.

Each column is worked out from the column before it, and nothing older is needed. Keeping the best cash for each of the three situations, day by day, and building each day's values from the previous day's is called dynamic programming.

Solution Approach

Turning the table into code means settling four things: why trying every plan is too slow, what to remember from one day to the next, how each day's three values follow from the day before, and which value is the answer.

Trying every plan

Why not list every plan and keep the most profitable one? Each day offers a choice, so the plans multiply. Counting every allowed sequence of daily actions, the five days of Example 1 allow 21 plans, ten days allow 351, twenty days allow 97,229 and thirty days already allow 26,931,732.

The table avoids that. Many plans end a day in the same situation, and only the one with the most cash can matter afterwards, so each day keeps three numbers instead of every plan.

What to remember each day

Which numbers does the next day need? Only the last column of the table. The code keeps them in three variables: hold is the best cash while holding a share, sold the best cash on a day that ended with a sale, and rest the best cash while free to buy.

Before day 0 you have no share and 0 cash, so sold and rest start at 0. Holding a share is not possible yet, so hold starts at Integer.MIN_VALUE, the smallest int. Selling on day 0 then gives a hugely negative sold, the dash in the table, and it never wins a comparison. Since no price is negative, that addition cannot wrap around to a large positive value.

Moving from one day to the next

How does today's column follow from yesterday's? Each situation has its own rule, read off the arrows in the picture, with p as today's price:

  • Sold today is yesterday's hold plus p, because only a share held at the end of yesterday can be sold today.
  • Holding a share is the larger of yesterday's hold, keeping the share, and yesterday's rest minus p, buying today. A day that ended with a sale counts in sold, not in rest, so nothing is bought the day after a sale.
  • Free to buy is the larger of yesterday's rest, doing nothing, and yesterday's sold, whose cooldown is today.

All three rules read yesterday's values, but the code overwrites the variables in place, so the order matters. First sold is updated, while hold is still yesterday's. Then hold is updated, while rest is still yesterday's. Last comes rest. It needs yesterday's sold, which is gone by then, so that value is saved beforehand in a variable named prevSold.

Reading off the answer

Which value is the answer after the last day? Ending while holding a share means money was spent on a share that is never sold, so that cannot beat the other two. The answer is the larger of sold and rest. In Example 2 there is one day: sold is hugely negative and rest is 0, so the answer is 0.

Java Solution

The method maxProfit works in these steps:

  1. First, set up the three situations: hold starts at Integer.MIN_VALUE, and sold and rest start at 0.
  2. Go through the prices with one loop, where p is today's price. At the start of each day, save yesterday's sold in prevSold.
  3. Sell today: set sold to hold + p.
  4. Keep or buy: set hold to the larger of hold and rest - p.
  5. Wait: set rest to the larger of rest and prevSold.
  6. After the loop, return the larger of sold and rest.

The main method runs both examples, a short array where the cooldown changes the answer, prices that only fall, and an eight-day array with two trades.

Java
public class BestTimeBuySellStockWithCooldown {

    public static int maxProfit(int[] prices) {
        int hold = Integer.MIN_VALUE;  // best cash while holding a share
        int sold = 0;                  // best cash on a day we just sold (cooldown next)
        int rest = 0;                  // best cash, not holding, free to buy
        for (int p : prices) {
            int prevSold = sold;
            sold = hold + p;                    // sell today
            hold = Math.max(hold, rest - p);    // keep holding, or buy today
            rest = Math.max(rest, prevSold);    // stay out; yesterday's sale ends its cooldown
        }
        return Math.max(sold, rest);
    }

    public static void main(String[] args) {
        System.out.println(maxProfit(new int[] {1, 2, 3, 0, 2}));
        System.out.println(maxProfit(new int[] {1}));
        System.out.println(maxProfit(new int[] {1, 4, 2, 7}));
        System.out.println(maxProfit(new int[] {5, 4, 3, 2, 1}));
        System.out.println(maxProfit(new int[] {3, 3, 5, 0, 0, 3, 1, 4}));
    }
}

Running it prints:

Output
3
0
6
0
6

The 3 and the 0 at the top match Examples 1 and 2. The 6 on the third line comes from [1, 4, 2, 7]. Buying at 1, selling at 4, then buying at 2 and selling at 7 would earn 3 + 5 = 8, but that second purchase falls on the cooldown day. The best allowed plan is a single trade from 1 to 7.

The fourth line is 0 because [5, 4, 3, 2, 1] only falls, so the best plan is never to buy. The last line, 6, comes from [3, 3, 5, 0, 0, 3, 1, 4]: buy at 3 and sell at 5 on day 2, wait on day 3, then buy at the second 0 on day 4 and sell at 4 on day 7.

Saving prevSold is what enforces the cooldown. If the last update used the new sold instead, a sale today would make tomorrow a buying day. With that change, the third line prints 8 instead of 6.

Complexity

The work is one pass over the prices, carrying three numbers from each day to the next.

  • Time: O(n), because the loop visits each of the n daily prices once and does three updates for it.
  • Space: O(1), because only hold, sold, rest and prevSold are kept, however many days there are.

Charging a fee per sale instead of a waiting day is Stock with Transaction Fee.