KatInterview

Best Single Round-Trip Gain Across Tickers in an Unordered Log

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinghash-mapsortinggreedy

Last updated

Find the largest gain from buying and later selling the same ticker on a strictly later date, given an unsorted log with duplicate dates; tests grouping, sorting and careful running-minimum updates.

Best Single Round-Trip Gain Across Tickers in an Unordered Log

You are given a log of price observations for several stocks. Each entry is a list [date, symbol, price]:

  • date: a string in "YYYY-MM-DD" format.
  • symbol: an uppercase ticker string such as "AAPL".
  • price: a positive integer.

The entries are not guaranteed to be in any particular order.

You may carry out exactly one round trip: purchase one share of a stock at the price in one entry, then sell one share of that same stock at the price in another entry whose date is strictly later than the purchase date. The gain is sell_price - buy_price.

Return the largest gain that any valid round trip can produce. If no valid round trip has a gain greater than zero (for instance, every ticker has fewer than two entries, or every ticker only loses value over time), return 0.

Details

  • Both entries of a round trip must have the same symbol.
  • The sell date must be strictly after the buy date. Two entries with the same date and symbol can never be paired with each other.
  • Several entries may share the same date and symbol.
  • Because dates are in YYYY-MM-DD form, comparing them as plain strings gives chronological order.

Function

Implement best_round_trip_gain(records), where records is a list of [date, symbol, price] entries, returning an integer: the maximum gain, or 0 if none is positive.

Constraints

  • 0 <= len(records) <= 2 * 10^5
  • Every date is a valid "YYYY-MM-DD" string.
  • 1 <= price <= 10^9
  • An empty log yields 0.

Examples

Example 1

Input: best_round_trip_gain([['2024-01-03', 'AAPL', 100], ['2024-01-01', 'AAPL', 90], ['2024-01-02', 'GOOG', 200], ['2024-01-04', 'GOOG', 150]])

Output: 10

Example 2

Input: best_round_trip_gain([['2024-05-01', 'TSLA', 300], ['2024-05-02', 'TSLA', 250], ['2024-05-03', 'TSLA', 200]])

Output: 0

Example 3

Input: best_round_trip_gain([['2024-07-10', 'NVDA', 500]])

Output: 0

Hints

Hint 1

Entries of different tickers never interact, so split the log by symbol and solve each ticker separately.

Hint 2

Within one ticker, sort by date and sweep forward while remembering the cheapest price seen on earlier dates. Checking all pairs is too slow for 2*10^5 entries.

Hint 3

Handle entries that share a date as a batch: evaluate every one of them as a possible sale against the minimum from strictly earlier dates, and only afterwards merge that day's lowest price into the running minimum.