Best Time to Buy and Sell Stock
Find the biggest profit from one buy and one later sell, tracking the cheapest price seen so far.
The problem
You get an array prices where prices[i] is the price of a stock on day i. You may buy once and sell once, and the sale has to happen on a later day than the purchase. Return the largest profit you can make, or 0 if no trade makes money.
Input prices = [9, 4, 7, 3, 8, 6]
Output 5
Buy on day 3 at price 3 and sell on day 4 at price 8.
Input prices = [6, 5, 5, 2]
Output 0
The price never rises after any day, so the best choice is not to trade.
Key constraint: Up to 100,000 days, so trying every buy day with every sell day (about 5 billion pairs) is too slow.
How to spot the pattern
- You pick a start and a later end to make a difference as large as possible.
- For each possible sell day, only the cheapest earlier price matters.
The idea
Think of a window from a buy day on the left to a sell day on the right. For any sell day, the best buy day is the cheapest day before it, so the window's left edge only ever needs to jump to a new lowest price. Walk through the days once, remember the lowest price so far, and at each day check the profit of selling today.
Brute force: Try every buy day with every later sell day, which takes O(n^2) time.
Step by step
- 1Set
minPriceto the first price andbest = 0. - 2For each price, compute
price - minPrice, the profit of selling today, and updatebestif it is larger. - 3If
priceis belowminPrice, make it the newminPrice, which moves the window's start to today. - 4Return
best.
See the pattern move
The sliding window pattern on a small example. Step through it, or press play.
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = prices[0] # cheapest day so far: the left edge of the window
best = 0
for price in prices:
best = max(best, price - min_price) # sell today
min_price = min(min_price, price)
return bestComplexity
Time
O(n)
Space
O(1)
One pass that keeps just the lowest price so far and the best profit.
Watch out for
- Subtracting the overall minimum from the overall maximum: the highest price may come before the lowest one, and you can't sell before you buy.
- Returning a negative number when prices only fall; the answer is 0 then, because you can skip trading.
Follow-up questions
What if you can make as many trades as you like?
Add up every rise from one day to the next, max(0, prices[i] - prices[i - 1]), because any profit can be split into those daily steps. That is Best Time to Buy and Sell Stock II.
What if you must rest for a day after every sale?
Then a choice today affects what you may do tomorrow, so you need dynamic programming with a few states per day: holding a stock, just sold, and resting. That is the cooldown version in the 2D dynamic programming section.
In Hinglish
Ab tak ka sabse sasta price yaad rakho, aur har din socho: aaj bechu toh kitna profit hoga?