PracticeNeetCode ↗LeetCode ↗
Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit from buying on one day and selling on a later day. Return 0 if no profit is possible.
min_price to infinity and max_profit to 0.min_price, update min_price.profit = price - min_price and update max_profit if it's larger.max_profit.Time: O(n) — Space: O(1)
def maxProfit(prices: list[int]) -> int:
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
else:
max_profit = max(max_profit, price - min_price)
return max_profitHow the solution above works, piece by piece.
min_price = the cheapest day so far (the best day to have bought); max_profit starts at 0 because not trading is allowed.min_price. Selling on the day you buy earns nothing, so there's nothing else to do.price - min_price; keep it if it beats the best so far.Running it on prices = [7, 1, 5, 3, 6, 4]:
price − min_price; the best of those is the answer. Buying must come before selling, which the left-to-right order guarantees.Striver (takeUforward) — Best Time to Buy and Sell Stock, Brute-Optimal