Practice Best Time to Buy and Sell Stock for free
- 1,500+ real interview questions
- An adaptive learning engine
- Mock system design interviews
- Mock behavioral interviews
- Code in 14 languages
- Video and drawn walkthroughs
The problem
prices is an array of integers: prices[i] is what one share of a stock costs on day i.
You may make one trade: buy a share on one day and sell it on a later day. The profit is the sell price minus the buy price. Return the largest profit you can make. If every trade would lose money or break even, make no trade and return 0.
Constraints
- 2 <=
prices.length<= 10^4 - 0 <=
prices[i]<= 10^4 - The sell day must come after the buy day
Example
- Input
prices = [5, 6, 2, 9, 1, 7, 0]- Output
7
Buy at 2 and sell the next day at 9: 9 - 2 = 7.
How to solve it
Why buying at the lowest price fails
The first instinct is to buy at the lowest price and sell at the highest. Here the lowest price is the 0, with nothing after it to sell on. So you take the lowest price that still has a day after it: buy at 1, sell at 7, make 6. That's a real trade, and it isn't the best one.
Trying every pair is always right: for each buy day, every later sell day, keeping the best profit. On the example that's 21 trades, 13 of them losing money, and the best is 7: buy at 2, sell at 9. Start with this one in the interview. It's O(n²), and this problem allows 10,000 days.
Fix the day you sell
Turn it around. Instead of picking a buy day and hunting for the sale, fix the day you sell. Selling on day 3 at 9, you could have bought at 5, 6 or 2, and 2 wins. Once the sell day is fixed, only the cheapest price before it matters, and that's true of every sell day.
So you don't need the pairs. Walk the prices once and keep two numbers: the lowest price so far and the best profit so far. On each day, work out what selling today would make, today's price minus the lowest so far, and keep it if it beats the best. Then, if today is cheaper than the lowest so far, it becomes the new lowest.
Watch what happens when the lowest price drops to 1, after the best trade is already found.
Best Time to Buy and Sell Stock([5,6,2,9,1,7,0])
The run starts on [5,6,2,9,1,7,0].
When the price falls to 1, the lowest so far moves down and the 7 stays. A new low only helps the days after it, and the trade from 2 to 9 is still a real trade. That's why the best profit is never reset. Selling at 7 after buying at 1 makes 6, close but not enough, and the 0 on the last day has no sale after it.
Why one pass is enough
The best trade sells on some day. When the loop reaches that day, it's already holding the cheapest price before it, so that exact trade is checked and kept. Starting the best profit at 0 covers prices that only fall: every sale loses money, nothing beats 0, and 0 means make no trade. The problem promises at least two days; in an interview, ask whether the list can be empty.
As many trades as you like
Next they'll let you buy and sell as many times as you want, holding one share at a time. Now take every rise: whenever tomorrow's price is higher than today's, add the difference. On the example that's 5 to 6, 2 to 9 and 1 to 7, so 1 + 7 + 6 = 14. Holding through several days earns exactly the sum of each day's change, and any drop in there only costs you, so collecting every rise and skipping every drop is the most any set of trades can make. The cost doesn't change: one pass, O(1) space.
Python solution
from typing import List
class Solution:
def max_profit(self, prices: List[int]) -> int:
current_min = prices[0]
max_profit = 0
for i in range(1, len(prices)):
if prices[i] - current_min > max_profit:
max_profit = prices[i] - current_min
if prices[i] < current_min:
current_min = prices[i]
return max_profitTime and space complexity
- Time O(n)
- Each day is looked at once, with one subtraction and two comparisons.
- Space O(1)
- Two numbers, the lowest price so far and the best profit so far, however many days there are.