Cheapest so far
Find the best buy-then-sell profit by remembering the lowest price seen. About 8 minutes.
Sell today, having bought at the cheapest day so far
You have a share's price for each day, and you may buy once and sell once, later. What's the most you could have made?
Suppose you sell today. The best day to have bought was the cheapest day before today. So walk through the days keeping the lowest price seen so far. Each day, work out today's price minus that lowest price, and keep the best profit you've seen.
lowest 7. best 0.
Not trading is allowed
If the price only ever falls, every trade loses money. The sensible choice is not to trade at all, which makes 0. So the best profit starts at 0, and a loss never replaces it.
For 7, 1, 5, 3, 6, 4: buy at 1, sell at 6, profit 5.
lowest = float("inf")
best = 0
for price in prices:
lowest = min(lowest, price)
best = max(best, price - lowest)
return bestThe lowest price so far is 3, the best profit so far is 4, and today's price is 9. What's the best profit now?
- A6
- B4
- C9
Show the answer
6. Selling at 9 after buying at 3 makes 6, which beats 4.
Best single trade
You get the price of a share on each day. You may buy once and sell once on a later day. Return the largest profit you can make, or 0 if no trade makes money.
prices = [7, 1, 5, 3, 6, 4] → 5
0 ≤ n ≤ 1,000,000 · 0 ≤ each price ≤ 10^9