Best Single Round-Trip Gain Across Tickers in an Unordered Log
Arrays & HashingAuto-graded · 23 test casesLast 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-DDform, 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
dateis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the classic single buy/sell problem with three twists: several tickers, unsorted input, and repeated dates.
- Group by ticker. Only entries with the same symbol can be paired, so each ticker is an independent subproblem.
- Sort each group by date.
YYYY-MM-DDstrings sort chronologically, so no date parsing is needed. - Sweep date by date. Keep
min_prior_price, the lowest price on dates strictly before the current date. For each distinct date, find that date's lowest and highest price. The best sale on that date gives a candidateday_max - min_prior_price(if a prior minimum exists). Only after that, fold the day's lowest price intomin_prior_price.
Updating the running minimum only after the whole date has been evaluated guarantees that entries sharing a date are never paired with each other.
The answer is the largest candidate over all tickers, starting from 0, which covers the "no profitable trade" case.
Why it is correct
Take any valid trade: buy at b on date d1, sell at s on date d2 > d1. When the sweep reaches d2, all earlier dates (including d1) have been merged, so min_prior_price <= b, and day_max >= s. The candidate is therefore at least s - b. Conversely, every candidate uses a real price from a strictly earlier date as the buy and a real price from the current date as the sell, so it is a valid trade and never overestimates. Hence the maximum candidate equals the true optimum.
Complexity
- Time: O(n log n), dominated by sorting the per-ticker lists (sizes sum to n); grouping and the sweep are O(n).
- Space: O(n) for the grouped lists.
Reference solution
from typing import List
def best_round_trip_gain(records: List[List]) -> int:
by_symbol = {}
for date, symbol, price in records:
by_symbol.setdefault(symbol, []).append((date, price))
best = 0
for trades in by_symbol.values():
trades.sort()
min_prior_price = None
i = 0
while i < len(trades):
date = trades[i][0]
day_min = trades[i][1]
day_max = trades[i][1]
j = i + 1
while j < len(trades) and trades[j][0] == date:
price = trades[j][1]
day_min = min(day_min, price)
day_max = max(day_max, price)
j += 1
if min_prior_price is not None:
best = max(best, day_max - min_prior_price)
if min_prior_price is None:
min_prior_price = day_min
else:
min_prior_price = min(min_prior_price, day_min)
i = j
return best