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 if no trade makes money. For example, prices give and give .
Short answer
One pass tracking the running minimum: time, 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 ). This replaces the naive 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