Finding the Python best time to buy and sell stock solution means identifying the greatest possible profit from a chronological list of prices while ensuring that the purchase occurs before the sale. This classic programming problem teaches an efficient technique called a single-pass scan, and the same reasoning appears in algorithm interviews, trading simulations, and financial data analysis.
Introduction
Suppose prices contains the price of one stock at different times:
prices = [7, 1, 5, 3, 6, 4]
The best strategy is to buy at 1 and sell at 6, producing a profit of 5. In real terms, buying at the lowest price and selling at the highest price sounds simple, but the highest price might occur before the lowest price. A valid solution must therefore respect the order of the data Simple, but easy to overlook..
The standard version of this problem allows only one buy and one sell. It also assumes that you cannot sell before buying and that doing no transaction is allowed. If no profit is possible, the correct result is usually 0 Turns out it matters..
The Core Python Solution
The most efficient approach tracks two values while moving through the list:
- The lowest price encountered so far
- The highest profit that could have been achieved so far
For every new price, calculate the profit from buying at the previous minimum and selling at the current price. Then update the minimum price if the current price is lower.
def max_profit(prices: list[int]) -> int:
if not prices:
return 0
minimum_price = prices[0]
best_profit = 0
for price in prices[1:]:
best_profit = max(best_profit, price - minimum_price)
minimum_price = min(minimum_price, price)
return best_profit
Example:
prices = [7, 1, 5, 3, 6, 4]
print(max_profit(prices)) # 5
The function returns 5 because it finds the valid pair 1 and 6.
How the Algorithm Works
Using [7, 1, 5, 3, 6, 4], the calculation proceeds as follows:
- Start with a minimum price of `