Coding interview problems › Arrays & Hashing
#️⃣ Arrays & Hashing Easy
Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock explained: track the cheapest price so far and the best profit in one O(n) pass. Tested Python, common mistakes, live visual.
Also searched as: stock buy and sell maximum profit · max profit one transaction
Try it live Free
Prefix Sums & Kadane
Watch Kadane scan once and carry a running value. Here the running value is the lowest price so far, and each day's profit is today minus that low.
The problem
You get a list of daily stock prices. You may buy on one day and sell on a later day, once. Return the maximum profit you can make, or 0 if no profitable trade exists.
Buy at 1, sell at 6.
Prices only fall, so do not trade.
The key insight
If you sell on day j, the best buy day is just the cheapest day before j. So walk once, remember the minimum price seen so far, and at each day check the profit of selling today. It is Kadane's idea in disguise: the running minimum plays the role of dropping a bad past.
Step-by-step approach
- Set
lowto infinity andbest = 0. - For each price
p: ifp < low, updatelow = p. - Otherwise compute
p - lowand updatebestif it is larger. - Return
best.
Python solution
def max_profit(prices):
low = float("inf")
best = 0
for p in prices:
if p < low:
low = p # cheapest buy so far
else:
best = max(best, p - low)
return bestComplexity
A single pass that keeps two numbers: the lowest price so far and the best profit.
Common mistakes
- Taking
max(prices) - min(prices), which ignores that you must buy before you sell. - Returning a negative number when prices only fall; the answer should be 0 (do not trade).
- Mixing this up with the unlimited-transactions variant, where you add every upward step instead.
Frequently asked questions
What is the time and space complexity of Best Time to Buy and Sell Stock?
O(n) time and O(1) space with the running-minimum solution. The pair-checking brute force is O(n²).
How is this related to Kadane's algorithm?
Take the daily price differences; the best profit is the maximum subarray sum of those differences (or 0). The running-minimum version is the same idea without building the difference array.
What if I can trade many times?
With unlimited transactions and no fees, add up every positive day-to-day increase. That greedy sum is the maximum profit.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Arrays & Hashing Hash Tables lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.