Skip to content

Best single buy-then-sell profit from a price list

Question

An array gives a stock's price on each successive day. You may buy once and later sell once (the sale must be on a strictly later day). Describe an algorithm returning the largest achievable profit, or 00 if no trade makes money. For example, prices [7,1,5,3,6,4][7,1,5,3,6,4] give 55 and [7,6,4,3,1][7,6,4,3,1] give 00.

Short answer

One pass tracking the running minimum: O(n)O(n) time, O(1)O(1) space. Scan left to right, keeping the lowest price seen so far; at each day the best sale today is price minus that minimum, and you keep the largest such value (starting at 00). This replaces the naive O(n2)O(n^2) check of all buy/sell pairs.

Adapted from OpenQuant; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question