Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

One trade: the best profit

Easy · Target 10 minutes · Dynamic programming · Type asked atAmazonGoldman SachsBloomberg

prices[i] is the price of a stock on day i. Choose one day to buy and a later day to sell. Return the largest profit possible, or 0 if no trade makes money.

Examples

InputOutputWhy
prices = [7,1,5,3,6,4]5Buy at 1, sell at 6.
prices = [7,6,4,3,1]0Prices only fall: do not trade.
prices = [2,4,1]2Buy at 2, sell at 4; the later 1 comes too late.

Constraints

  • 1 ≤ prices.length ≤ 10⁵
  • 0 ≤ prices[i] ≤ 10⁴

Hints

Hint 1

Fix the selling day. The best buying day is the cheapest day before it.

Hint 2

Keep the lowest price seen so far while scanning.

Hint 3

Equivalently, this is the maximum subarray of the daily price changes.

Where people lose marks

  • Selling before buying (taking the global maximum minus the global minimum).
  • Returning a negative profit instead of 0.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.