Best Time to Buy and Sell Stock IV

Find the most profit from buying and selling one share, with at most k transactions.

Given an integer k and an array prices that holds the price of one share on each day, in order, return the largest profit you can make with at most k transactions. A transaction is one buy followed by one sell. You can hold only one share at a time, so you must sell before you buy again. If no plan makes money, the answer is 0.

Example 1
Input: k = 2, prices = [2, 4, 1]
Output: 2
Explanation: buy at 2, sell at 4.
Example 2
Input: k = 2, prices = [3, 2, 6, 5, 0, 3]
Output: 7
Explanation: buy at 2, sell at 6; buy at 0, sell at 3.
Solution

The Idea

Picture a trader who watches the price of one share for six days: 3, 2, 6, 5, 0 and 3, as in Example 2. The trader may buy the share, sell it later, and make that round trip at most k times. With k = 2, the best plan buys at 2 and sells at 6 for a profit of 4, then buys at 0 and sells at 3 for 3 more, 7 in total.

Is the answer simply the k biggest price rises? Try the prices 1, 5, 2, 8 with k = 1. The rises go from 1 to 5 and from 2 to 8, worth 4 and 6. Taking the bigger one gives 6, but buying at 1 and selling at 8 gives 7. One transaction can stretch over several rises, so the best move on any day depends on what the trader did on the days before it.

So walk through the days one at a time and keep track of the trader's cash. Cash starts at 0: buying at 2 makes it -2, and selling later at 6 brings it up to 4. At any moment the trader is in one of a few stages: holding share 1, after sale 1, holding share 2, after sale 2. For each stage, remember the most cash the trader can have in it so far.

Look at the picture below. Each row is a day, and each column is one stage, with the name the code gives it: buy[1] for holding share 1, sell[1] for after sale 1, and so on.

The table for Example 2 with k = 2: one row per day, and columns for the most cash while holding share 1, after sale 1, while holding share 2 and after sale 2. The 4 after sale 1 on day 3 pays for share 2 on day 5, and selling it on day 6 gives 7.

On day 3, the column "after sale 1" becomes 4: share 1 was bought at 2 on day 2, and selling it at 6 turns -2 into 4. On day 5 the price is 0, and buying share 2 out of that 4 leaves 4 - 0 = 4 under "holding share 2". On day 6, selling share 2 at 3 gives 4 + 3 = 7 under "after sale 2", the answer.

Each new row needs only the rows above it and the day's price, never a full list of past trades. Working out the best cash for every stage on day 1, then building day 2 from day 1, and so on, is called dynamic programming.

Solution Approach

Listing every plan is the slow way, and the table avoids it. Turning the table into code means settling four things: what one entry means, where the entries start, why one row is enough, and when k is so large that no table is needed.

Trying every plan

Why not list every plan and keep the best? A plan picks up to k pairs of a buy day and a later sell day, with no two pairs overlapping. The number of such plans grows very fast with the number of days, and many plans start the same way. The table handles a shared start once: a row keeps the best cash per stage, whichever plan led there.

What one entry means

What exactly does one entry hold? The entry buy[j] is the most cash the trader can have after buying share number j and before selling it. The entry sell[j] is the most cash after sale number j. On a day with price p, each entry has two choices:

  • Holding share j: buy[j] = max(buy[j], sell[j - 1] - p). Either keep the share bought earlier, or buy today, paying p out of the cash after sale j - 1.
  • After sale j: sell[j] = max(sell[j], buy[j] + p). Either keep the cash from an earlier sale, or sell share j today for p.

Look at day 4 in the picture. Under "holding share 2" the cash moves from -2 to -1, because the 4 after sale 1, minus that day's price 5, beats buying at 2. Share j is always paid from the cash after sale j - 1, so the transactions come one after another.

Starting values

Where does the table start? Before day 1 nothing has been sold, so every sell[j] starts at 0. Nothing is held either, so every buy[j] starts at Integer.MIN_VALUE, the smallest int, which any real purchase beats. One extra entry, sell[0], stays 0 for good: it is the cash before the first transaction, and share 1 is paid from it.

Keeping one row

Does the code need the whole table? Each day needs only the day before and its own price, so two arrays of k + 1 entries, buy and sell, are enough, and each day overwrites them. Within a day, buy[j] is updated before sell[j] reads it, so buy[j] + p never adds to the starting Integer.MIN_VALUE.

That order also lets the code sell share j - 1 and buy share j on the same day, or buy and sell one share on the same day. Both moves earn nothing, so they never raise an entry above what real trades allow. A same-day buy and sell does pass the cash from sale j - 1 on to sale j, which is why sell[k] also covers plans with fewer than k transactions.

When k is large

What if k is huge? Each transaction needs a buy day and a later sell day, so a list of prices leaves room for at most prices.length / 2 of them. When k reaches that, the limit never stops the trader, and the best plan takes every rise from one day to the next, as in Best Time to Buy and Sell Stock II. For 1, 5, 2, 8 with k = 2, that is 4 + 6 = 10. Testing for this case before anything else also keeps the code from making arrays of k + 1 entries for a k of a billion.

Java Solution

The method maxProfit works in these steps:

  1. First, check whether k is at least prices.length / 2. If so, add every rise from one day to the next into profit and return it.
  2. Otherwise, make two arrays of k + 1 entries: buy, filled with Integer.MIN_VALUE, and sell, left at 0.
  3. Go through the days with a loop that takes each price as p. Inside it, a second loop moves j from 1 up to k and updates buy[j], then sell[j], with the two choices.
  4. After the last day, return sell[k], the most cash after at most k transactions.

The main method runs both examples and Example 2 with k = 1. Then it tries 1, 5, 2, 8 with k = 1 and k = 2, a longer list, falling prices, k = 0, no prices at all, and Example 2 with a k of one billion.

Java
import java.util.Arrays;

public class BestTimeBuySellStockIV {

    public static int maxProfit(int k, int[] prices) {
        if (k >= prices.length / 2) {         // the limit can never bind: take every rise
            int profit = 0;
            for (int i = 1; i < prices.length; i++) {
                profit += Math.max(0, prices[i] - prices[i - 1]);
            }
            return profit;
        }
        int[] buy = new int[k + 1];           // buy[j]: most cash while holding share j
        int[] sell = new int[k + 1];          // sell[j]: most cash after sale j
        Arrays.fill(buy, Integer.MIN_VALUE);  // no share can be held before any day
        for (int p : prices) {
            for (int j = 1; j <= k; j++) {
                buy[j] = Math.max(buy[j], sell[j - 1] - p);   // keep holding, or buy today
                sell[j] = Math.max(sell[j], buy[j] + p);      // keep the cash, or sell today
            }
        }
        return sell[k];
    }

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

Running it prints:

Output
2
7
4
7
10
6
0
0
0
7

Example 1 gives 2 and Example 2 gives 7. With k = 1, Example 2 drops to 4, since one trade from 2 to 6 beats one from 0 to 3. The fourth line, 7 for 1, 5, 2, 8 with k = 1, is the trade from 1 to 8, not the single rise of 6. The fifth line, 10, comes from the shortcut: four prices leave room for two transactions, so both rises count.

The sixth line, 6, is for 3, 3, 5, 0, 0, 3, 1, 4 with k = 2, for example buying at 0, selling at 3, then buying at 1 and selling at 4. Falling prices, k = 0 and an empty list each print 0. The last line is 7 again, now with k = 1,000,000,000, and the shortcut returns it without making any arrays.

Without the shortcut, that last call would ask for two arrays of 1,000,000,001 int values, about 4 GB each. On a test run with a heap limit of about 1.5 GB, a version without the check stopped with java.lang.OutOfMemoryError: Java heap space.

Complexity

The work is one update of every stage for every day, unless the shortcut answers first.

  • Time: O(n × k), because each of the n prices runs the inner loop over the k transactions, with two Math.max calls each; when the shortcut applies, a single pass over the prices takes O(n).
  • Space: O(k), because buy and sell hold k + 1 entries each however many days there are, while the shortcut keeps only profit.

With k fixed at 2, the same four stages fit in four variables: see Best Time to Buy and Sell Stock III.