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 pricesprices[i]i
Example 1
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
Output: 0
Explanation: the prices only fall, so every trade would lose money, and the answer is 0.
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.
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: minPricebest
Handling each new price
What happens when the next day's price arrives? If it is lower than minPriceminPrice
Otherwise, selling today earns today's price minus minPricebest
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
minPriceInteger.MAX_VALUEintprices[0]
Java Solution
The method maxProfit
- First, set
tominPrice , so the first price will replace it, and setInteger.MAX_VALUE , the largest profit so far, to 0.best - Walk through the array with one
loop, taking each day'sfor in turn.price - If
is lower thanprice , store it inminPrice : today is a cheaper day to buy.minPrice - Otherwise, compute
, the profit of selling today, and store it inprice - minPrice if it beats the old value.best - After the loop, return
, the largest profit any single trade could make.best
The main
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:
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]bestminPrice
The fourth line, 2, comes from [2, 4, 1]
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,
Complexity
The method looks at each price once and keeps only two numbers between days.
- Time: O(n), because the
loop visits each of the n daily prices once, with one comparison and at most one subtraction per day.for - Space: O(1), because only
andminPrice are kept, however many days the array covers.best
When you may buy and sell as many times as you like, see