Top-K Price Harvest from Tiered Stock Levels
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Tests whether a candidate can reformulate a greedy revenue problem into summing the largest elements across union-of-range price sets and implement an O(n log n) layer-sweep solution.
Problem
A warehouse manages n product lines. Each product line i (0-indexed) holds stock[i] units. A queue of m buyers arrives one at a time. Each buyer purchases exactly one unit of one product line (the warehouse decides which), as long as that product line still has units available.
How the sale price is determined:
When a buyer purchases a unit from product line i, they pay a price equal to the current unit count of that product line at the moment of the transaction — that is, before the unit is removed. The unit count then drops by 1.
For example, if product line i currently holds 4 units and a buyer purchases from it, that buyer pays 4 and the count becomes 3 for the next transaction.
The warehouse can freely decide, for each buyer in turn, which product line to sell from (as long as it has positive stock). Your task is to determine the maximum total revenue the warehouse can collect across all buyers.
If m exceeds the total units available across all product lines, the surplus buyers simply receive nothing; revenue comes only from actual sales.
You must design a solution that remains efficient even when n, m, and individual stock values are very large (up to 10⁹).
Input
n— a positive integer, the number of product lines.stock— a list ofnnon-negative integers, wherestock[i]is the initial unit count of product linei.m— a non-negative integer, the number of buyers.
Output
Return a single integer: the maximum total revenue achievable.
Constraints
1 ≤ n ≤ 10⁵0 ≤ stock[i] ≤ 10⁹0 ≤ m ≤ 10⁹- The answer fits in a 64-bit signed integer (Python handles this natively).
Examples
Example 1
Input: max_warehouse_revenue(2, [2, 3], 3)
Output: 7
Example 2
Input: max_warehouse_revenue(3, [5, 1, 4], 4)
Output: 16
Example 3
Input: max_warehouse_revenue(4, [10, 10, 10, 10], 7)
Output: 67
Example 4
Input: max_warehouse_revenue(3, [1, 2, 3], 10)
Output: 10
Hints
Hint 1
Think about what set of prices is theoretically available for sale across all product lines. A product line with initial stock q can generate prices q, q-1, q-2, ..., 1 — one per unit. To maximize revenue, which prices from that full collection should you pick?
Hint 2
Once you see the answer as 'sum the m largest values from the union of all those price ranges', think about how to compute that sum without enumerating every individual price. Prices form horizontal bands when you sort the stock values and look at them as a histogram.
Hint 3
Sort stocks in descending order and sweep downward band by band. At each band, you know exactly how many product lines are 'active' (their stock reaches this level). Use closed-form arithmetic-series formulas to consume entire bands in O(1), stopping as soon as you've accounted for all m buyers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reformulating the problem
A product line with initial stock q can generate at most q sales, at prices q, q-1, q-2, ..., 1 — always in that descending order regardless of how its sales are interleaved with other product lines. So the complete set of available prices across all product lines is:
P = { 1, 2, ..., stock[0] } ∪ { 1, 2, ..., stock[1] } ∪ ... (multiset union)
To maximize revenue from m buyers, simply pick the min(m, |P|) largest prices from P and sum them. This is achievable: selling top prices from each product line means taking a top-prefix of that line's price list, which corresponds to selling its most expensive units first — always a valid strategy.
Why naive simulation is too slow
The obvious greedy — repeatedly sell the unit from the product line with the highest current stock (using a max-heap) — runs in O(m log n). When m can reach 10⁹ that is far too slow.
The layer-sweep insight
Visualize the sorted stock values as a histogram. Prices in P correspond to cells in this histogram. Sweeping from the tallest bar downward, every horizontal "band" between two consecutive distinct stock heights contains a fixed number of active product lines.
Sort the positive stock values in descending order, then iterate over consecutive pairs of distinct values level and next_level. In the band spanning prices next_level+1 through level, exactly active product lines each contribute one unit per price level. The total units in the band is active * (level - next_level), and their sum is an arithmetic series computable in O(1):
active × (level - next_level) × (level + next_level + 1) / 2
Two cases arise for each band:
- Band fits entirely within remaining demand. Add the full band's revenue and move on.
- Band exceeds remaining demand. Use
divmod(remaining, active)to find how many complete rows fit, add their revenue (another arithmetic series), then add the revenue from the leftover partial row (all units at the same price). Return immediately.
Correctness
- Every price in
Pis visited exactly once by the sweep, in non-increasing order. - The sweep stops after exactly
min(m, |P|)prices are counted. - Within a partial band, all active product lines offer the same price at each row, so it doesn't matter which specific lines fill the partial row — all choices yield the same revenue.
- Edge cases:
m = 0or all stocks zero → return 0.m ≥ |P|→ the loop exhausts all bands and returnsΣ stock[i] * (stock[i] + 1) / 2.
Complexity
- Time: O(n log n) for sorting + O(n) for the sweep. The arithmetic is O(1) per band, independent of
mor the magnitude of stock values. - Space: O(n) for the sorted list.
Compare this to the heap simulation at O(m log n) — the layer sweep eliminates the dependence on m entirely after the sort.
Full solution
from typing import List
def max_warehouse_revenue(n: int, stock: List[int], m: int) -> int:
# Filter out empty product lines and sort by stock descending.
levels = sorted((s for s in stock if s > 0), reverse=True)
if m <= 0 or not levels:
return 0
revenue = 0
active = 0 # product lines whose stock reaches the current price level
i = 0
remaining = m # buyers still to be served
while i < len(levels):
level = levels[i]
# Advance past all product lines that share this same stock level.
j = i
while j < len(levels) and levels[j] == level:
j += 1
active += j - i
# The current band spans prices: next_level+1, ..., level
# (active product lines each contribute one unit per price in this range).
next_level = levels[j] if j < len(levels) else 0
available = active * (level - next_level)
if remaining <= available:
# This band contains more units than we need — consume partially.
full_layers, remainder = divmod(remaining, active)
if full_layers:
# Full rows cover prices level, level-1, ..., level-full_layers+1.
revenue += active * (
full_layers * level - full_layers * (full_layers - 1) // 2
)
# One partial row at price (level - full_layers).
revenue += remainder * (level - full_layers)
return revenue
# Consume the entire band using the arithmetic-series closed form.
revenue += active * (level - next_level) * (level + next_level + 1) // 2
remaining -= available
i = j
# All units were sold before serving all m buyers.
return revenue