Online store~15 min2s · 256 MBtarget O(n) time, O(n) spacehashing
A marketplace app lets people post offers to buy or to sell an item at a fixed price. At the end of the day the app matches offers. A buy offer and a sell offer for the same item at the same price trade as many units as both sides can supply.
The operations team wants a quick report of how many units traded in total. The order in which the offers were posted does not change the total.
Write matched_units(items, prices, sides, quantities).
i is for item items[i] at the price prices[i]. If sides[i] is 0 it is an offer to buy, and if it is 1 it is an offer to sell. It covers quantities[i] units.buy be the total units offered to buy and sell the total units offered to sell. Exactly min(buy, sell) units trade there.Input: items = [1, 1, 2, 1, 1, 2], prices = [50, 50, 70, 50, 60, 70], sides = [0, 1, 0, 1, 0, 1], quantities = [5, 3, 4, 4, 2, 6]
Output: 9The table groups the offers by item and price.
| Item | Price | Units to buy | Units to sell | Units traded |
|---|---|---|---|---|
| 1 | 50 | 5 | 7 | 5 |
| 2 | 70 | 4 | 6 | 4 |
| 1 | 60 | 2 | 0 | 0 |
At item 1 and price 50, 5 units are offered to buy and 3 + 4 = 7 to sell, so 5 units trade. At item 2 and price 70, 4 units trade. At item 1 and price 60 nobody sells. The table shows the totals.
Input: items = [4], prices = [10], sides = [0], quantities = [9]
Output: 0A buy offer with no sell offer trades nothing.
Input: items = [1, 2], prices = [10, 10], sides = [0, 1], quantities = [5, 5]
Output: 0The price is the same, but the items differ, so nothing trades.
1 ≤ items.length ≤ 100,000 (offers); the four lists have the same length1 ≤ items[i] ≤ 1,000,000 (item ids), 1 ≤ prices[i] ≤ 10,000,000 (units), sides[i] is 0 or 11 ≤ quantities[i] ≤ 1,000,000The total can reach 10^11, so it needs a 64-bit result.
Matching each buy offer against every sell offer costs about n × n / 4 steps, 2.5 × 10^9 at n = 100,000. Grouping the offers by item and price needs one pass. At each group the answer is a single min, so one more pass over the groups finishes the job.