Best Time to Buy and Sell Stock with Transaction Fee
Find the most money you can make from a stock's daily prices when every buy and sell together costs a fee.
Given an array pricesprices[i]ifeefee
Example 1
Output: 8
Explanation: buy at 1 and sell at 8, a profit of 8 - 1 - 2 = 5. Then buy at 4 and sell at 9, a profit of 9 - 4 - 2 = 3. Together they make 8.
Example 2
Output: 6
Explanation: buy at 1 and sell at 10, a profit of 10 - 1 - 3 = 6.
The Idea
Picture a trader who watches one stock for six days, at the prices of Example 1: 1, 3, 2, 8, 4 and 9. Every time the trader buys a share and later sells it, a broker takes 2 for that trade.
Without a fee, every rise in price is worth taking: buy just before it and sell at its top, as in
Keeping the share from 1 straight through to 8 does better. That one trade earns 8 - 1 - 2 = 5, and 4 to 9 adds 3, for 8. Not selling at 3 and buying again at 2 saved a whole fee. So whether selling today is wise depends on prices still to come. How can we decide, day by day, without knowing the future?
Instead of deciding, keep every good option open. At the end of any day, the trader is in one of two situations: holding a share or holding none. For each day, we keep the most money the trader can have in each situation. Money counts from 0 at the start, so buying at 1 leaves -1.
Look at the picture above. On day 0, the row labelled "best money holding a share" shows -1, because holding a share on day 0 means buying it at 1. The row labelled "best money with no share" shows 0, because nothing has happened yet.
Each later day fills its two boxes from the two boxes of the day before. To end a day with no share, the trader either had none yesterday too, or sells today. On day 3, selling at 8 turns day 2's holding money, -1, into -1 + 8 - 2 = 5, which beats the 0 from staying out.
To end a day holding a share, the trader either kept yesterday's share, or buys today with yesterday's no-share money. On day 4, buying at 4 turns the 5 into 5 - 4 = 1, which beats keeping the old share at -1. On day 5, selling at 9 gives 1 + 9 - 2 = 8.
Why is one number per box enough? Two traders who both hold a share tonight face exactly the same choices tomorrow, so the one with more money stays ahead. The answer is the last box in the "best money with no share" row, 8, since a share still held at the end was paid for and never sold.
Filling rows like these box by box, where each box is built from boxes already filled, is called dynamic programming. Here each day's two boxes need only the two boxes of the day before.
Solution Approach
Turning the two rows into code means settling four things: why trying every plan is too slow, what the two numbers start at, where the fee is paid, and how much of the two rows to keep.
Trying every plan
Why not list every way to trade and keep the best? On each day the trader either acts (buys, or sells the share held) or waits. With n days that gives 2n plans, already 1,073,741,824 for 30 days. The two rows look at each day once instead.
Starting values
What does day 0 hold? The best money holding a share is -prices[0]
Where the fee is paid
When does the fee come off? Once per transaction, so it is taken only when selling: yesterday's holding money, plus today's price, minus fee
Keeping only yesterday
Does the code need both full rows from the picture? Each day reads only the day before, so two variables are enough. The one catch is order: the code works out both of today's numbers from yesterday's, so the new no-share number goes into a temporary variable until the holding number has been updated.
Java Solution
The method maxProfit
- First, set
, the best money holding a share, tohold , and-prices[0] , the best money with no share, to 0.cash - A loop then walks over the remaining days, with
from 1, and puts the day's price intoi .p - Inside the loop, work out
as the larger ofnewCash (stay out) andcash (sell today).hold + p - fee - Next, update
to the larger ofhold (keep the share) andhold (buy today), which still reads yesterday'scash - p .cash - Then copy
intonewCash , ready for the next day.cash - After the last day, return
.cash
The main
public class BestTimeBuySellStockWithTransactionFee {
public static int maxProfit(int[] prices, int fee) {
int hold = -prices[0]; // best money while holding a share: bought on day 0
int cash = 0; // best money while holding no share
for (int i = 1; i < prices.length; i++) {
int p = prices[i];
int newCash = Math.max(cash, hold + p - fee); // stay out, or sell today
hold = Math.max(hold, cash - p); // keep the share, or buy today
cash = newCash;
}
return cash;
}
public static void main(String[] args) {
System.out.println(maxProfit(new int[] {1, 3, 2, 8, 4, 9}, 2));
System.out.println(maxProfit(new int[] {1, 3, 7, 5, 10, 3}, 3));
System.out.println(maxProfit(new int[] {1, 3}, 2));
System.out.println(maxProfit(new int[] {9, 7, 4, 1}, 1));
System.out.println(maxProfit(new int[] {5}, 2));
System.out.println(maxProfit(new int[] {1, 3, 2, 8, 4, 9}, 0));
}
}
Running it prints:
8
6
0
0
0
13
The 8 and the 6 match the examples. In Example 2, two trades, 1 to 7 and 5 to 10, would earn 3 + 2 = 5 after fees, so the single trade from 1 to 10, worth 6, wins.
The third line is 0 for [1, 3]cashcash
Look at the last line, 13. With no fee, the code takes every rise of Example 1: 2 + 6 + 5 = 13. That is 5 more than the 8 on the first line. Of that 5, 4 is the two fees, and 1 is the dip from 3 to 2 that the fee-paying trader holds through instead of selling.
The starting value of hold
Complexity
The work is one pass over the days, with a fixed amount of work on each.
- Time: O(n), because the loop visits each of the n days once and makes two
choices for it.Math.max - Space: O(1), because only yesterday's two numbers are kept, in
andhold , instead of both full rows from the picture.cash
The same two rows, with one waiting day forced after each sale, solve