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 that holds the price of a stock on each day, in order, return the most profit you can make with at most two trades. A trade is buying one share and selling it on a later day. You can hold only one share at a time, so the second buy must come after the first sale. If no trade makes money, return 0.

Example 1
Input: prices = [3, 3, 5, 0, 0, 3, 1, 4]
Output: 6
Explanation: buy at 0 and sell at 3, then buy at 1 and sell at 4, for 3 + 3 = 6.
Example 2
Input: prices = [1, 2, 3, 4, 5]
Output: 4
Explanation: buy at 1 and sell at 5; one trade is enough.
Example 3
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: the price only falls, so every trade would lose money.
Solution

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.

A table for the prices 3, 3, 5, 0, 0, 3, 1, 4 with one row per stage: holding 1st share, sold 1st share, holding 2nd share, sold 2nd share. The highlighted boxes are 0 on day 4, 3 on day 6, 2 on day 7 and 6 on day 8.

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 p arrives? Each stage keeps its old value or moves on from the stage before it, whichever leaves more cash. The code keeps the four stages in variables named buy1, sell1, buy2 and sell2:

  • Holding the 1st share: buy1 = Math.max(buy1, -p), since buying from cash 0 leaves -p.
  • Sold the 1st share: sell1 = Math.max(sell1, buy1 + p), selling the share held in buy1.
  • Holding the 2nd share: buy2 = Math.max(buy2, sell1 - p), paying for it out of the first profit.
  • Sold the 2nd share: sell2 = Math.max(sell2, buy2 + p).

The four lines run in this order, so sell1 may read the buy1 that changed a moment ago, on the same day. That only adds the choice of buying and selling on the same day, which earns nothing. On the same 20,000 random lists, a version that read only the previous day's values gave the same answers.

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 buy1 and buy2 at Integer.MIN_VALUE, the smallest int, so the first price replaces them. The two sold stages start at 0, because selling nothing leaves the cash where it began.

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 sell2 is never less than sell1, and both start at 0, which is the answer when no trade pays.

Java Solution

The method maxProfit works in these steps:

  1. First, create the four stages: buy1 and buy2 start at Integer.MIN_VALUE, and sell1 and sell2 start at 0.
  2. Go through the prices with a for loop, taking each day's price as p.
  3. Inside the loop, update the stages in order with Math.max: buy1 from -p, sell1 from buy1 + p, buy2 from sell1 - p, and sell2 from buy2 + p.
  4. After the loop, return sell2, the most cash after at most two trades.

The main method runs the three examples, the ten prices where the best single trade is not part of the best pair, a single day, and an empty array.

Java
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:

Output
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 keeps its starting 0.

Those starting values matter. If buy1 and buy2 started at 0 instead, the method would act as if a share had been bought for nothing. On [7, 6, 4, 3, 1] that version returns 7 rather than 0, and on Example 1 it returns 9 rather than 6.

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 Math.max updates for it.
  • Space: O(1), because the four stages live in four int variables, however many days the array covers.

When more than two trades are allowed, the same stages become arrays: see Best Time to Buy and Sell Stock IV.