Best Time to Buy and Sell Stock
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Given daily prices, choose one day to buy and a later day to sell so the profit is as large as possible.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1For a fixed selling day, which buying day would be best?
- Hint 2It is the cheapest day before it. Can you keep that value updated as you walk?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
You track gold prices every day. Each morning you ask only one thing: "If I had bought on the cheapest day I have seen so far and sold today, how much would I earn?" You keep a sticky note with the lowest price so far and a second note with the best profit seen. That is all you need, no looking back at every old day.
- The obvious way
Try every buy day with every later sell day: O(n²).
- The key insight
If you sell today, the best purchase is the lowest price so far. So walk through the days keeping the lowest price seen and the best profit found: each day first check "today minus lowest", then update the lowest.
- The algorithm
- Sticky note 1: lowest price so far (start very high). Sticky note 2: best profit (start 0).
- For each day: profit if sold today = today's price minus the lowest. Keep it if it beats the best.
- Then, if today is cheaper than the lowest, update the lowest.
- After the last day the best profit is the answer (0 if prices only fall).
Watch it run
Exampleprices = [7, 1, 5, 3, 6, 4]
Day 1, price 7. Nothing to sell yet. Lowest so far = 7.
lowest 7, best profit 0
Where people slip
- You may not sell before you buy: check today's profit BEFORE updating the lowest with today's price.
- If prices only fall, the answer is 0, not negative.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def max_profit(prices):
lowest = float("inf") # cheapest price seen so far
best = 0 # best profit seen so far
for price in prices:
best = max(best, price - lowest) # sell today?
lowest = min(lowest, price) # is today the cheapest day yet?
return bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.