KatInterview

Best Single Buy-Sell Gain from Daily Quotes

Greedy & IntervalsAuto-graded · 20 test cases
EasyAuto-gradedGreedy & Intervalsgreedyarraysrunning-minimum

Last 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^5
  • 0 <= 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.