Maximum Profit from Dated Stock Trade Records
RampSoftware Engineer · Online AssessmentLast updated
This question evaluates a candidate's ability to design an efficient single-pass algorithm for grouped time-series data, tracking per-symbol running minimums to compute maximum achievable profit. It tests array processing, hash-map grouping, and edge-case handling for unsorted records, commonly used in coding interviews to assess practical algorithmic problem-solving rather than pure theory.
Maximum Profit from Dated Stock Trade Records
You are given a log of stock trades. Each trade is a record [date, symbol, price]:
date— a calendar date as a string in"YYYY-MM-DD"format.symbol— the stock's ticker, an uppercase string (e.g.,"AAPL").price— the trade price as a positive integer (the price in cents, so every value is exact).
The records may appear in any order — they are not sorted by date.
You want to make exactly one buy-then-sell transaction:
- Buy one share of some stock on one day, then sell that same stock on a strictly later day.
- The profit of a transaction is
sell_price - buy_price. - The buy and sell must share the same
symbol, and the selldatemust be strictly after the buydate.
Return the maximum profit achievable from a single such transaction. If no transaction yields a positive profit (for example, fewer than two records exist for every symbol, or every symbol only declines over time), return 0.
Input / Output
- Input:
records, a list of[date, symbol, price]entries. - Output: a single integer — the maximum achievable profit, or
0if none is positive.
Examples
Example 1:
records = [
["2024-01-03", "AAPL", 100],
["2024-01-01", "AAPL", 90],
["2024-01-02", "GOOG", 200],
["2024-01-04", "GOOG", 150]
]
Output: 10
Explanation: For AAPL, buy at 90 on 2024-01-01 and sell at 100 on 2024-01-03, giving a profit of 10. For GOOG, the price only falls (200 down to 150), so it offers no profit. The best single transaction is 10.
Example 2:
records = [
["2024-05-01", "TSLA", 300],
["2024-05-02", "TSLA", 250],
["2024-05-03", "TSLA", 200]
]
Output: 0
Explanation: TSLA only declines, so no profitable buy-then-sell exists.
Example 3:
records = [
["2024-07-10", "NVDA", 500]
]
Output: 0
Explanation: A single record cannot form a buy-then-sell pair.
Constraints
0 <= len(records) <= 2 * 10^5.- Each
dateis a valid"YYYY-MM-DD"string; lexicographic string comparison matches chronological order. 1 <= price <= 10^9.- Multiple records may share the same
dateandsymbol; a buy and a sell on the same date do not form a valid transaction, because the sell date must be strictly later than the buy date.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.