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 pricesprices[i]i
Example 1
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
Output: 0
Explanation: with a single day there is no later day to sell on.
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.
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: holdsoldrest
Before day 0 you have no share and 0 cash, so soldrestholdInteger.MIN_VALUEintsold
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
- Sold today is yesterday's
plushold , because only a share held at the end of yesterday can be sold today.p - Holding a share is the larger of yesterday's
, keeping the share, and yesterday'shold minusrest , buying today. A day that ended with a sale counts inp , not insold , so nothing is bought the day after a sale.rest - Free to buy is the larger of yesterday's
, doing nothing, and yesterday'srest , whose cooldown is today.sold
All three rules read yesterday's values, but the code overwrites the variables in place, so the order matters. First soldholdholdrestrestsoldprevSold
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 soldrestsoldrest
Java Solution
The method maxProfit
- First, set up the three situations:
starts athold , andInteger.MIN_VALUE andsold start at 0.rest - Go through the prices with one loop, where
is today's price. At the start of each day, save yesterday'sp insold .prevSold - Sell today: set
tosold .hold + p - Keep or buy: set
to the larger ofhold andhold .rest - p - Wait: set
to the larger ofrest andrest .prevSold - After the loop, return the larger of
andsold .rest
The main
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:
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]
The fourth line is 0 because [5, 4, 3, 2, 1][3, 3, 5, 0, 0, 3, 1, 4]
Saving prevSoldsold
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 andrest are kept, however many days there are.prevSold
Charging a fee per sale instead of a waiting day is