progress

~/problems / Sliding window

Best Time to Buy and Sell Stock

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

prices[d] is a share's price on day d. You may buy once and sell on a strictly later day. Write best_profit(prices: list[int]) -> int that returns the largest profit prices[sell] - prices[buy], or 0 if no trade makes money.

best_profit([8, 3, 6, 1, 5, 4])    # 4   (buy at 1, sell at 5)
best_profit([9, 7, 4, 2])          # 0   (prices only fall)
best_profit([2, 11])               # 9
best_profit([5])                   # 0
  • 1 <= len(prices) <= 2 * 10^5; prices are in [0, 10^9].
  • ⭐ Bonus: trying every buy day with every later sell day is O(n²) and still passes; speed tests with 200,000 prices earn a star in O(n) time.
Show hint

if you sell on day d, which buy day is best? Keep that answer up to date as d moves forward.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc