Best Time to Buy and Sell Stock
You may complete at most one buy and one later sell. Return maximum profit, or 0 if no profit is possible.
Answers use simple, clear English.
Quick interview answer
Track the minimum price seen so far. At each price, candidate profit = price - minSoFar; keep the maximum. One left-to-right pass with O(1) extra space.
Detailed answer
Track the minimum price seen so far. At each price, candidate profit = price - minSoFar; keep the maximum. One left-to-right pass with O(1) extra space. Multiple transactions need a different greedy/DP. Mention fees only if the interviewer adds them.
Full explanation
Multiple transactions need a different greedy/DP. Mention fees only if the interviewer adds them.
Real example & use case
A day-trading bot limited to one long position computes the best entry/exit on daily closes.
Pros & cons
Pros: O(n)/O(1), classic pattern. Cons: single transaction only; ignores fees and shorting.
Code example
def max_profit(prices: list[int]) -> int:
min_price = float('inf')
best = 0
for p in prices:
min_price = min(min_price, p)
best = max(best, p - min_price)
return bestPractice code · python (view only · no execution)
def max_profit(prices: list[int]) -> int:
min_price = float('inf')
best = 0
for p in prices:
min_price = min(min_price, p)
best = max(best, p - min_price)
return best