Calculate Max Trading Returns from Multi-Asset Feed
Greedy & IntervalsAuto-graded · 21 test casesLast 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:
date: A string representing the timestamp in ISOYYYY-MM-DDformat.symbol: A string representing the asset ticker (e.g.,"AAPL").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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem can be decomposed into two main components: data organization and greedy accumulation.
-
Ticker Independence: Holding or trading one stock has no impact on trades in another stock. Therefore, we can group the log entries by ticker symbol and analyze each symbol independently. The total maximum profit will simply be the sum of maximum profits obtained from each distinct stock.
-
Temporal Alignment: Because the records arrive unsorted and interleaved, we must reconstruct the chronological sequence of prices for each ticker. ISO date strings formatted as
YYYY-MM-DDhave the property that lexicographical comparison matches chronological order. Sorting the tuples(date, price)for each ticker arranges the prices in chronological order without needing explicit date parsing. -
Greedy Profit Accumulation: For a single chronologically sorted price array $P = [p_0, p_1, \dots, p_{k-1}]$, we want to maximize profit with unlimited transactions while holding at most 1 unit at any time. Any trade spanning from day $i$ to day $j$ ($i < j$) yields profit $p_j - p_i$, which can be expanded as a sum of adjacent differences: $$p_j - p_i = \sum_{t=i+1}^{j} (p_t - p_{t-1})$$
To maximize this total, we should simply include every single positive step $(p_t - p_{t-1} > 0)$ and avoid holding during negative steps. Summing all positive adjacent price differences gives the optimal profit for that ticker.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N)$ where $N$ is the total number of records. Grouping into hash maps takes $\mathcal{O}(N)$ time. Sorting each ticker's entries takes $\sum \mathcal{O}(k_i \log k_i) \le \mathcal{O}(N \log N)$ time overall.
- Space Complexity: $\mathcal{O}(N)$ to store records organized by ticker symbol in a hash map.
Python Reference Code
from collections import defaultdict
from typing import List
def maximum_profit(records: List[List[object]]) -> int:
prices_by_stock = defaultdict(list)
# Step 1: Group records by ticker symbol
for date, stock, price in records:
prices_by_stock[stock].append((date, price))
total = 0
# Step 2 & 3: Chronologically sort and accumulate positive price changes
for prices in prices_by_stock.values():
prices.sort() # Sorts by date lexicographically
for i in range(1, len(prices)):
gain = prices[i][1] - prices[i - 1][1]
if gain > 0:
total += gain
return total