Best Time to Buy and Sell Stock

Find the largest profit from buying a stock on one day and selling it on a later day.

Given an array prices, where prices[i] is a stock's price on day i, choose one day to buy one share and a later day to sell it. Return the largest profit such a trade can make, or 0 if no trade makes a profit. Days are counted from 0.

Example 1
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: buy on day 1 (price 1) and sell on day 4 (price 6), for a profit of 6 - 1 = 5. Selling on day 0 at price 7 is not allowed, because day 0 comes before the buy.
Example 2
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: the prices only fall, so every trade would lose money, and the answer is 0.
Solution

The Idea

You have probably heard the advice "buy low, sell high". Here we know a stock's price for every day in advance, and we may make one trade: buy one share on some day and sell it on a later day. The profit is the selling price minus the buying price.

In Example 1 the prices are 7, 1, 5, 3, 6 and 4, for days 0 to 5. The highest price is 7 and the lowest is 1, but the 7 is on day 0, before the 1. A share bought on day 1 cannot be sold on day 0, so 7 - 1 = 6 is not a real trade. The order of the days matters.

So which pairs of days should we check? Trying every buy day with every later sell day works, but six days already give 15 such pairs. Turn the question around and fix the sell day instead: if you sell today, which day should you have bought on?

On the cheapest day before today. Whatever today's price is, a lower buying price only means more profit. So for each day we need just one number from the past: the lowest price so far.

Look at the picture below. Each bar is one day's price, and the dashed line labelled lowest price so far follows the cheapest price up to each day.

Prices 7, 1, 5, 3, 6, 4 on days 0 to 5 as bars. A dashed line marks the lowest price so far: 7 on day 0, then 1 from day 1 on. The window runs from the buy on day 1 to the sell on day 4, and the profit is 6 - 1 = 5.

The dashed line starts at 7 on day 0 and drops to 1 on day 1. It stays at 1 after that, because no later price is lower. On day 4 the price is 6, and the arrow labelled profit shows its gap above the line: 6 - 1 = 5. No other bar rises higher above the line, so 5 is the answer.

The bracket at the top, labelled window, shows the same trade another way. The prices from the buy day to the sell day form a stretch of the array, called a window. Its right edge is today and moves forward one day at a time. Its left edge is the buy day, and it jumps forward only when a new lowest price appears. A window whose two edges only ever move forward like this is called a sliding window.

Solution Approach

Turning that idea into code means settling three things: what to remember from the days already passed, what to do with each new price, and what to return when no trade makes money.

What to remember

Why not simply try every pair of days? Two loops, one for the buy day and one inside it for each later sell day, do find the answer. But n days give n × (n - 1) / 2 pairs: 15 for six days, and 4,999,950,000 for 100,000 days. Remembering the lowest price so far replaces the inner loop with a single subtraction.

So what has to be kept from the days already passed? Only two numbers: minPrice, the lowest price so far, and best, the largest profit found so far. The buy day itself is not needed, because the profit depends only on its price.

Handling each new price

What happens when the next day's price arrives? If it is lower than minPrice, it becomes the new minPrice, and the window's left edge jumps to today. Buying and selling on the same day earns nothing, so there is no profit to check on that day.

Otherwise, selling today earns today's price minus minPrice, and best keeps the larger of that profit and its old value.

When no trade makes money

What if the prices only fall, as in Example 2? Then every day brings a new lowest price, and no profit is ever computed. best starts at 0 and only grows, so the answer is 0, never a negative number.

minPrice starts at Integer.MAX_VALUE, the largest value a Java int can hold, so the first price always replaces it. The code never reads prices[0] on its own, so an empty array is safe too.

Java Solution

The method maxProfit works in these steps:

  1. First, set minPrice to Integer.MAX_VALUE, so the first price will replace it, and set best, the largest profit so far, to 0.
  2. Walk through the array with one for loop, taking each day's price in turn.
  3. If price is lower than minPrice, store it in minPrice: today is a cheaper day to buy.
  4. Otherwise, compute price - minPrice, the profit of selling today, and store it in best if it beats the old value.
  5. After the loop, return best, the largest profit any single trade could make.

The main method runs both examples, two arrays where a low price comes after a high one, three equal prices, a single day, and an empty array.

Java
public class BestTimeToBuyAndSellStock {

    public static int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;     // cheapest day to buy, up to today
        int best = 0;
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price;             // a cheaper buying day
            } else {
                best = Math.max(best, price - minPrice);   // sell today
            }
        }
        return best;
    }

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

Running it prints:

Output
5
0
6
2
0
0
0

The 5 and the 0 at the top match Examples 1 and 2. Look at the third line, 6, from [4, 9, 1, 7]. Buying at 4 and selling at 9 earns 5, and best holds that 5 when the price 1 arrives. minPrice then drops from 4 to 1, and on the last day 7 - 1 = 6 beats the 5.

The fourth line, 2, comes from [2, 4, 1]. Its highest price is 4 and its lowest is 1, but the 1 is on the last day, so nothing can be sold after it. Subtracting the lowest price from the highest would give 3 here, and 6 for Example 2, whose answer is 0.

The last three lines are all 0. Three equal prices make a profit of 0, a single day has no later day to sell on, and the empty array never enters the loop.

The original implementation, BestTimeToBuyAndSellStock.java, is on GitHub.

Complexity

The method looks at each price once and keeps only two numbers between days.

  • Time: O(n), because the for loop visits each of the n daily prices once, with one comparison and at most one subtraction per day.
  • Space: O(1), because only minPrice and best are kept, however many days the array covers.

When you may buy and sell as many times as you like, see Best Time to Buy and Sell Stock II.