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 kpricesk
Example 1
Output: 2
Explanation: buy at 2, sell at 4.
Example 2
Output: 7
Explanation: buy at 2, sell at 6; buy at 0, sell at 3.
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 kk = 2
Is the answer simply the kk = 1
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]sell[1]
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
Trying every plan
Why not list every plan and keep the best? A plan picks up to k
What one entry means
What exactly does one entry hold? The entry buy[j]jsell[j]jp
- Holding share j:
. Either keep the share bought earlier, or buy today, payingbuy[j] = max(buy[j], sell[j - 1] - p) out of the cash after salep .j - 1 - After sale j:
. Either keep the cash from an earlier sale, or sell sharesell[j] = max(sell[j], buy[j] + p) today forj .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 jj - 1
Starting values
Where does the table start? Before day 1 nothing has been sold, so every sell[j]buy[j]Integer.MIN_VALUEintsell[0]
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 + 1buysellbuy[j]sell[j]buy[j] + pInteger.MIN_VALUE
That order also lets the code sell share j - 1jj - 1jsell[k]k
When k is large
What if kprices.length / 2kk = 2k + 1k
Java Solution
The method maxProfit
- First, check whether
is at leastk . If so, add every rise from one day to the next intoprices.length / 2 and return it.profit - Otherwise, make two arrays of
entries:k + 1 , filled withbuy , andInteger.MIN_VALUE , left at 0.sell - Go through the days with a loop that takes each price as
. Inside it, a second loop movesp from 1 up toj and updatesk , thenbuy[j] , with the two choices.sell[j] - After the last day, return
, the most cash after at mostsell[k] transactions.k
The maink = 1k = 1k = 2k = 0k
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:
2
7
4
7
10
6
0
0
0
7
Example 1 gives 2 and Example 2 gives 7. With k = 1k = 1
The sixth line, 6, is for 3, 3, 5, 0, 0, 3, 1, 4 with k = 2k = 0k = 1,000,000,000
Without the shortcut, that last call would ask for two arrays of 1,000,000,001 intjava.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
transactions, with twok calls each; when the shortcut applies, a single pass over the prices takes O(n).Math.max - Space: O(k), because
andbuy holdsell entries each however many days there are, while the shortcut keeps onlyk + 1 .profit
With k