~/problems / Sliding window

Best Time to Buy and Sell Stock

easy ~12 min

prices[d] is the price of one share on day d. You may buy one share on some day and sell it on a strictly later day, at most once. Write best_profit(prices: list[int]) -> int that returns the largest profit prices[sell] - prices[buy] you can make, or 0 if no trade makes money (you can always choose not to trade).

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].
  • Trying every buy day with every later sell day is O(n²), too slow for the large tests. Aim for O(n) time and O(1) extra space.
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