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 prices, where prices[i] is the price of one stock on day i, and a number fee, return the most profit you can make. You may buy and sell as many times as you like, but you can own at most one share at a time, so you must sell before you buy again. Each transaction, one buy and the sell that follows it, costs fee once.

Example 1
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
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
Input: prices = [1, 3, 7, 5, 10, 3], fee = 3
Output: 6
Explanation: buy at 1 and sell at 10, a profit of 10 - 1 - 3 = 6.
Solution

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 Best Time to Buy and Sell Stock II. Here the rises are 1 to 3, 2 to 8 and 4 to 9. After paying 2 for each trade they earn 0, 4 and 3, which is 7 in all.

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.

Prices 1, 3, 2, 8, 4, 9 with fee 2. Two rows of boxes, one per day: best money holding a share is -1, -1, -1, -1, 1, 1 and best money with no share is 0, 0, 0, 5, 5, 8. Arrows show selling at 8 for 5, buying at 4 for 1, and selling at 9 for 8.

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], the cost of buying on day 0, and the best money with no share is 0. Starting the holding number at 0 would mean the first share was free.

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. Buying costs just the price. A rise smaller than the fee then never pays for itself, and the trader keeps holding or stays out.

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 works in these steps:

  1. First, set hold, the best money holding a share, to -prices[0], and cash, the best money with no share, to 0.
  2. A loop then walks over the remaining days, with i from 1, and puts the day's price into p.
  3. Inside the loop, work out newCash as the larger of cash (stay out) and hold + p - fee (sell today).
  4. Next, update hold to the larger of hold (keep the share) and cash - p (buy today), which still reads yesterday's cash.
  5. Then copy newCash into cash, ready for the next day.
  6. After the last day, return cash.

The main method runs both examples, a rise equal to the fee, prices that only fall, a single day, and Example 1 again with no fee.

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

Output
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] with fee 2: selling at 3 gives -1 + 3 - 2 = 0, no better than never trading. The prices 9, 7, 4, 1 only fall, so every sale loses and cash stays 0. With the single price 5, the loop never runs and cash is still 0.

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 matters. Changed to 0, the same method returns 9 for Example 1 instead of 8, because the first share is then free.

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 Math.max choices for it.
  • Space: O(1), because only yesterday's two numbers are kept, in hold and cash, instead of both full rows from the picture.

The same two rows, with one waiting day forced after each sale, solve Best Time to Buy and Sell Stock with Cooldown.