Best Single Buy-Sell Gain from Daily Quotes
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Find the largest gain from buying on one day and selling on a later day in a list of daily prices, returning 0 if no gain is possible.
Best Single Buy-Sell Gain from Daily Quotes
You are given a list quotes, where quotes[i] is the price of a single asset on day i. You may complete at most one trade: pick one day to buy and a strictly later day to sell, then collect the difference quotes[sell] - quotes[buy].
Return the largest gain you can obtain. If every possible trade loses money or breaks even, or if no trade is possible, return 0.
Rules
- The sell day must come after the buy day.
- You may also choose not to trade, which yields a gain of
0. - The result is never negative.
- The return value is a single integer.
Constraints
1 <= len(quotes) <= 10^50 <= quotes[i] <= 10^9
Examples
Example 1
Input: best_trade_gain([7, 1, 5, 3, 6, 4])
Output: 5
Example 2
Input: best_trade_gain([7, 6, 4, 3, 1])
Output: 0
Hints
Hint 1
A trade is decided by two days. If you fix the selling day, which earlier day is the best one to have bought on?
Hint 2
While scanning left to right, keep track of the lowest price seen so far. The best gain for selling today is today's price minus that lowest price.
Hint 3
Start the best gain at 0 so that falling or flat prices, and lists with a single day, naturally return 0. Do not just compute max minus min, because the order of days matters.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the prices once from left to right while maintaining two values:
lowest: the smallest price seen so far (the best possible day to have bought).best: the largest gain found so far, starting at0.
For each price, first update lowest, then compute price - lowest, which is the best gain achievable if we sell today. Update best if this gain is larger.
Why it is correct
Any trade buys on some day b and sells on a day s after it. For a fixed sell day, the gain is maximized by buying at the cheapest price among the earlier days, and lowest holds exactly that value. Taking the maximum over all sell days therefore covers the optimal buy for each of them, so the overall maximum is the true answer.
Updating lowest before computing the gain can produce a gain of 0 (buying and selling the same day), but that is harmless since 0 is the answer whenever no profitable trade exists. Starting best at 0 also handles a single-day list and strictly decreasing prices.
Simply computing max(quotes) - min(quotes) is wrong because the minimum may occur after the maximum.
Complexity
- Time: O(n), one pass.
- Space: O(1).
Reference solution
from typing import List
def best_trade_gain(quotes: List[int]) -> int:
lowest = float('inf')
best = 0
for price in quotes:
if price < lowest:
lowest = price
gain = price - lowest
if gain > best:
best = gain
return best