Best Time to Buy and Sell Stock III
Make the most money from at most two buy-and-sell trades on a list of daily stock prices.
Given an array prices
Example 1
Output: 6
Explanation: buy at 0 and sell at 3, then buy at 1 and sell at 4, for 3 + 3 = 6.
Example 2
Output: 4
Explanation: buy at 1 and sell at 5; one trade is enough.
Example 3
Output: 0
Explanation: the price only falls, so every trade would lose money.
The Idea
Suppose you could look back at a stock's price on each of the last eight days: 3, 3, 5, 0, 0, 3, 1, 4. You may buy one share and sell it later, and do that at most twice. How much could you have made?
With one trade, the best plan buys at 0 on day 4 and sells at 4 on day 8, for a profit of 4. Two trades do better. Buy at 0 on day 4 and sell at 3 on day 6, then buy at 1 on day 7 and sell at 4 on day 8. Each trade earns 3, so the total is 6.
The other examples show that two trades are a limit, not a rule. On the rising prices 1 to 5, a single trade from 1 to 5 already takes the whole rise of 4. On the falling prices 7 down to 1, every trade loses money, so the best plan is not to trade, and the answer is 0. So how do we find the best plan, with two trades, one or none, without trying every choice of buy and sell days?
Follow the cash instead of the trades. Cash starts at 0, buying at a price takes that price away, and selling adds it back. At any point the trader is at one of four stages: holding the 1st share, sold the 1st share, holding the 2nd share, or sold the 2nd share. For each stage, we keep the most cash the trader could have at that stage, using only the days seen so far.
Look at the picture below. The top two lines are the days and their prices. Below them, each row is one stage, and each box is the best cash so far for that stage at the end of that day.
On day 1 the price is 3, so the row labelled "holding 1st share" starts at -3: the share cost 3. On day 4 the price drops to 0, and buying then leaves 0 cash, which beats -3, so that row becomes 0. On day 6, selling that share at 3 raises the row labelled "sold 1st share" to 3.
On day 7, buying the second share at 1 out of those 3 leaves 2 in the row labelled "holding 2nd share". That row already shows 2 from day 4 (sell at 5 on day 3, buy at 0 on day 4), and the new plan ties it. On day 8, selling it at 4 brings the row labelled "sold 2nd share" to 2 + 4 = 6. That is the answer, and the orange arrows trace the four steps that led to it.
Notice what each box needs. A stage either stays as it was the day before, or the trader reaches it today from the stage above it, by buying or selling at today's price. Before the row labelled "holding 1st share" comes the stage where nothing has happened yet, with cash 0. Filling in the boxes day by day from earlier boxes, instead of trying every set of trade days, is called dynamic programming.
Solution Approach
Turning the four stages into code means settling four things: why the simpler plans are slow or wrong, how each stage changes in one day, what the stages start at, and which stage holds the answer.
Simpler plans
Is there an easier way? Two trades that do not overlap can always be split by some day, with the first trade before it and the second from that day on. So one simple way tries every split day, and on each side tries every buy day with every later sell day. For n days, that is on the order of n³ steps. It does give the right answers, which makes it a good check: on 20,000 random price lists of up to eight days, it agreed with the four-stage method every time.
A faster shortcut looks tempting: find the best single trade, then add the best trade in the days left before or after it. Take the ten prices 1, 2, 4, 2, 5, 7, 2, 4, 9, 0. The best single trade buys at 1 on day 1 and sells at 9 on day 9, for 8. Only day 10 is left, so the shortcut ends at 8. Yet buying at 1 and selling at 7, then buying at 2 and selling at 9, earns 6 + 7 = 13. The best pair of trades need not contain the best single trade.
Updating the stages each day
What changes when a new day with price pbuy1sell1buy2sell2
- Holding the 1st share:
, since buying from cash 0 leavesbuy1 = Math.max(buy1, -p) .-p - Sold the 1st share:
, selling the share held insell1 = Math.max(sell1, buy1 + p) .buy1 - Holding the 2nd share:
, paying for it out of the first profit.buy2 = Math.max(buy2, sell1 - p) - Sold the 2nd share:
.sell2 = Math.max(sell2, buy2 + p)
The four lines run in this order, so sell1buy1
Starting values
What should the stages hold before day 1? No share has been bought yet, so the two holding stages have no real value. The code starts buy1buy2Integer.MIN_VALUEint
Reading the answer
Which box holds the answer? It is the last box of the row labelled "sold 2nd share". It also covers plans with one trade or none. A second trade that buys and sells on the same day earns 0, so sell2sell1
Java Solution
The method maxProfit
- First, create the four stages:
andbuy1 start atbuy2 , andInteger.MIN_VALUE andsell1 start at 0.sell2 - Go through the prices with a
loop, taking each day's price asfor .p - Inside the loop, update the stages in order with
:Math.max frombuy1 ,-p fromsell1 ,buy1 + p frombuy2 , andsell1 - p fromsell2 .buy2 + p - After the loop, return
, the most cash after at most two trades.sell2
The main
public class BestTimeBuySellStockIII {
public static int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE; // holding the first share
int sell1 = 0; // first share sold
int buy2 = Integer.MIN_VALUE; // holding the second share
int sell2 = 0; // second share sold
for (int p : prices) {
buy1 = Math.max(buy1, -p); // keep, or buy the first share today
sell1 = Math.max(sell1, buy1 + p); // keep, or sell the first share today
buy2 = Math.max(buy2, sell1 - p); // keep, or buy the second share today
sell2 = Math.max(sell2, buy2 + p); // keep, or sell the second share today
}
return sell2;
}
public static void main(String[] args) {
System.out.println(maxProfit(new int[] {3, 3, 5, 0, 0, 3, 1, 4}));
System.out.println(maxProfit(new int[] {1, 2, 3, 4, 5}));
System.out.println(maxProfit(new int[] {7, 6, 4, 3, 1}));
System.out.println(maxProfit(new int[] {1, 2, 4, 2, 5, 7, 2, 4, 9, 0}));
System.out.println(maxProfit(new int[] {5}));
System.out.println(maxProfit(new int[] {}));
}
}
Running it prints:
6
4
0
13
0
0
Example 1 gives 6, the same as the last box in the row labelled "sold 2nd share". Then 4 for the rising prices comes from one trade, and 0 for the falling prices from no trade at all. The fourth line, 13, beats the 8 that the best-single-trade shortcut reaches on the same ten prices.
The last two lines are 0. With one price there is no later day to sell on, and with no prices the loop never runs, so sell2
Those starting values matter. If buy1buy2[7, 6, 4, 3, 1]
Complexity
The method reads each price once and keeps only four numbers.
- Time: O(n), because the loop visits each of the n daily prices once and does four
updates for it.Math.max - Space: O(1), because the four stages live in four
variables, however many days the array covers.int
When more than two trades are allowed, the same stages become arrays: see