KatInterview

Calculate Max Trading Returns from Multi-Asset Feed

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsarraysgreedysorting

Last updated

Process an unordered multi-asset market feed to find the maximum possible cumulative profit across all tickers.

You are given an unordered log of financial transactions from a stock market feed. Each entry in the log is a tuple containing three elements:

  1. date: A string representing the timestamp in ISO YYYY-MM-DD format.
  2. symbol: A string representing the asset ticker (e.g., "AAPL").
  3. price: A non-negative integer representing the asset's closing price on that date.

The records are provided out of order, with multiple ticker symbols mixed together. Each (symbol, date) pair is guaranteed to appear at most once in the dataset.

You want to evaluate the maximum profit possible by trading these assets under the following constraints:

  • You may execute an unlimited number of buy and sell transactions over time.
  • Positions in different ticker symbols are completely independent; you may hold positions in multiple distinct assets at the same time.
  • For any single ticker symbol, you can hold at most 1 share at a time. You must sell your existing share of a given stock before purchasing another share of the same stock.
  • Every transaction occurs at the exact price listed for that date.
  • There are no transaction fees, and you start and end with 0 shares of all assets.

Calculate and return the maximum cumulative profit achievable across all assets combined. If no profitable trade exists, return 0.

Constraints

  • 1 <= len(records) <= 2 * 10^5
  • Ticker strings consist of 1 to 10 alphanumeric characters.
  • Prices are non-negative integers: 0 <= price <= 10^6.
  • ISO dates format strictly follows YYYY-MM-DD.
  • The total output fits within a standard 64-bit signed integer.

Examples

Example 1

Input: maximum_profit([['2024-01-03', 'AAPL', 7], ['2024-01-01', 'AAPL', 1], ['2024-01-02', 'AAPL', 5], ['2024-01-01', 'MSFT', 10], ['2024-01-02', 'MSFT', 6]])

Output: 6

Hints

Hint 1

Since each stock is traded independently without cross-ticker restrictions, you can process each symbol individually.

Hint 2

Standard ISO 8601 date strings (`YYYY-MM-DD`) maintain chronological order when sorted lexicographically.

Hint 3

For a single time series of prices, greedily accumulating every positive step-by-step price increase yields the global maximum profit.