Maximize profit from a single buy/sell.
Skip to solutionKEEP THE
easyDSA
How do you find the best time to buy and sell a stock?
865 views
01
Understand the problem
arraysgreedy
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Track the minimum price seen so far and, at each day, compute price - minSoFar to update the best profit. One pass updates both, giving O(n) time and O(1) space. The trick is realizing you only need the lowest price to the left of each selling day.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Track the running minimum
Run Playgrounddef max_profit(prices):
min_price = float('inf')
best = 0
for price in prices:
min_price = min(min_price, price)
best = max(best, price - min_price)
return best
# --- demo ---
print(max_profit([7, 1, 5, 3, 6, 4])) # 5 (buy 1, sell 6)05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 9 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.