Sliding window · Easy
Best time to buy and sell
Return the largest profit from buying once and selling later. Return 0 if no profit is possible. Buy on one day and sell on a later day. Compare each sale against the cheapest earlier purchase.
Worked example
[7, 1, 5, 3, 6, 4] → 5
- Once the price reaches 1, keep that as the cheapest purchase.
- Selling later at 5 earns 4. Selling at 6 earns 5, the best profit.
Python solution
def solve(prices):
lowest = float('inf')
best = 0
for price in prices:
lowest = min(lowest, price)
best = max(best, price - lowest)
return bestTrack the lowest price seen so far and the best later sale.
Time: O(n) · Space: O(1)