Find the maximum profit from buying and selling a stock once.
This problem follows the Sliding Window Min pattern, commonly found in the Sliding Window category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Track minimum price seen so far. At each price, calculate profit from min.
You only need to track the minimum price seen so far — at each day, the best you could do is sell at today's price minus that minimum.
minPrice = infinity
maxProfit = 0
for price in prices:
minPrice = min(minPrice, price)
maxProfit = max(maxProfit, price - minPrice)
return maxProfitPractice Best Time to Buy and Sell Stock and similar Sliding Window problems with flashcards. Build pattern recognition through active recall.
Practice this problem