Maximum Revenue Under Stock-Indexed Pricing
Medium · Coding & Algorithms · Data Scientist · Online Assessment
Problem Statement
A warehouse stocks n distinct item categories indexed 0 through n - 1, where quantity[i] gives the initial unit count available for category i. Up to m buyers arrive one after another, and each buyer purchases a single unit from one category chosen by the seller (provided at least one category still has positive stock):
def maximize_revenue(n: int, quantity: List[int], m: int) -> int:
Unit prices depend dynamically on remaining inventory:
- Selling one unit from category
iwhenkunits of categoryiare currently left collectskin revenue and reduces categoryi's remaining stock tok - 1. - Categories with
0remaining units cannot be sold. - When
mexceeds the combined initial stock across allncategories, every unit in the warehouse is sold and the leftoverm - sum(quantity)buyers purchase nothing (0revenue).
Choose which category to sell at each step so that total revenue is as large as possible, and return that maximum revenue as an integer. Your algorithm must run fast even when n, m, and quantity[i] are very large.
Examples
Example 1
Input: n = 2, quantity = [3, 4], m = 3
Output: 10
Walk-through:
- Buyer 1 buys from category 1 (stock 4 -> 3), paying 4.
- Buyer 2 buys from category 0 (stock 3 -> 2), paying 3.
- Buyer 3 buys from category 1 (stock 3 -> 2), paying 3.
- Total revenue is 4 + 3 + 3 = 10.
Example 2
Input: n = 3, quantity = [6, 2, 5], m = 4
Output: 20
Walk-through:
- Selling from category 0 (6), category 0 (5), category 2 (5), and either category 0 or 2 (4) collects 6 + 5 + 5 + 4 = 20.
Example 3
Input: n = 3, quantity = [8, 8, 8], m = 5
Output: 38
Walk-through:
- The first three buyers take one unit from each category at price 8 (3 * 8 = 24), leaving [7, 7, 7].
- The next two buyers take one unit from two categories at price 7 (2 * 7 = 14), giving 24 + 14 = 38.
Example 4
Input: n = 3, quantity = [2, 0, 4], m = 9
Output: 13
Walk-through:
- Total stock across all categories is 2 + 0 + 4 = 6 < 9, so only 6 buyers can be served.
- Category 0 yields 2 + 1 = 3, category 1 yields 0, and category 2 yields 4 + 3 + 2 + 1 = 10, for 13 total.
Constraints
1 <= n <= 10^5len(quantity) == n0 <= quantity[i] <= 10^90 <= m <= 10^14
Step-by-step walkthrough
Picture each category's stock as a stack of price tags
Category
istarts withquantity[i]units. Because a buyer pays the current remaining count beforequantity[i]shrinks by1, selling units from a category with initial countqcollectsq, thenq - 1, thenq - 2, down to1.You can picture each category as a vertical stack of price tags sorted from
quantity[i]on top down to1at the bottom:quantity = [6, 2, 5] Category 0 Category 1 Category 2 [6] [5] [5] [4] [4] [3] [3] [2] [2] [2] [1] [1] [1]We serve up to
mbuyers, one unit each. Whenevermexceeds the combined stock across all categories, every available unit is sold and the leftover buyers pay0.Why greedy is optimal—and why one-by-one simulation is too slow
Which category should the next buyer purchase from? Always whichever category currently has the largest remaining stock:
- No valid sequence of at most
msales can earn more than the sum of themlargest price tags in the entire diagram. - Because every stack decreases from top to bottom, the largest remaining tag in the warehouse is always sitting right on top of some stack—never buried underneath a smaller tag!
Picking the largest remaining stock
mtimes is therefore guaranteed to collect themhighest prices.However, simulating one buyer at a time—even with a max-heap (a priority queue that extracts and updates the largest stock in
O(log n)time)—takesO(m log n)steps. Whenmandquantity[i]reach10^9, a billion heap operations time out. We need to sum entire bands of sales at once.- No valid sequence of at most
Key insight: slice all stacks horizontally with one cutoff price
Inspect the
4largest price tags in Example 2 (quantity = [6, 2, 5],m = 4): they are6,5,5, and one of the4s. Draw a horizontal line atcutoff_price = 4:quantity = [6, 2, 5], m = 4 Category 0 Category 1 Category 2 [6] \ [5] [5] / 3 units strictly ABOVE 4 (prices 6, 5, 5) ------------------------------------- <-- cutoff_price = 4 [4] <-- [4] 1 remaining buyer pays 4 [3] [3] [2] [2] [2] [1] [1] [1]Notice the clean split around
cutoff_price: 1. Every unit priced strictly abovecutoff_priceis sold (stock - cutoff_priceunits from each category withstock > cutoff_price). 2. Whatever buyers remain (customers_to_serve - units_sold_above) each buy one unit priced atcutoff_price.How do we find
cutoff_price? Letcount_units_above(t)be the total number of units priced strictly greater thant. Astrises from0tomax(quantity),count_units_above(t)shrinks monotonically (never increases) fromtotal_stockdown to0:quantity = [6, 2, 5], customers_to_serve = 4 t: 0 1 2 3 4 5 6 count_units_above: 13 10 7 5 3 1 0 <= 4? no no no no YES YES YES ^-- smallest t with <= 4 units above tBecause the
no / YEStransition is monotonic, binary search locates the smallest validcutoff_pricein at most~30steps (log2(10^9) ≈ 30)!Why are there always enough units priced at
cutoff_pricefor the remaining buyers? - Ifcutoff_price == 0, thencount_units_above(0) == total_stock == customers_to_serve, so0buyers remain. - Ifcutoff_price >= 1, thencutoff_price - 1failed the<= customers_to_servetest, meaningcount_units_above(cutoff_price - 1) > customers_to_serve. The gapcount_units_above(cutoff_price - 1) - count_units_above(cutoff_price)equals the exact number of units priced atcutoff_price, guaranteeing enough tied units to serve every remaining buyer!Code the helper and binary search
First we write
count_units_above, thenfind_cutoff_priceover[0, max(quantity)]:from typing import List def count_units_above(quantity: List[int], cutoff_price: int) -> int: """Count total units across all products priced strictly above cutoff_price.""" total_above = 0 for stock in quantity: if stock > cutoff_price: # A product with `stock` units offers prices stock, stock - 1, ..., 1, # so exactly (stock - cutoff_price) of its units cost > cutoff_price. total_above += stock - cutoff_price return total_above def find_cutoff_price(quantity: List[int], customers_to_serve: int) -> int: """Return the smallest price t >= 0 with at most customers_to_serve units above t.""" # Search range [low, high]: # high = max(quantity) always works because 0 units are priced above max(quantity). low = 0 high = max(quantity) while low < high: mid = (low + high) // 2 # As mid increases, count_units_above(mid) only decreases or stays equal. if count_units_above(quantity, mid) <= customers_to_serve: # mid has <= customers_to_serve units above it, so the smallest valid # cutoff is at or below mid; keep mid inside the search interval. high = mid else: # Strictly more than customers_to_serve units sit above mid, # so mid is too low and cannot be the cutoff. low = mid + 1 return lowSum each category's sold band with the arithmetic series formula
Once we know
cutoff_price, each category withstock > cutoff_pricesells all consecutive prices fromcutoff_price + 1throughstock.Instead of looping over those prices one by one, we apply the arithmetic series formula—the sum of consecutive integers from
firsttolastacrosscount = last - first + 1terms is(first + last) * count // 2:Example: stock = 6, cutoff_price = 3 Prices sold: 4 + 5 + 6 = 15 Formula: lowest = 3 + 1 = 4, highest = 6, count = 6 - 3 = 3 (4 + 6) * 3 // 2 = 30 // 2 = 15Notice that when
countis odd,lowestandhighestshare the same parity solowest + highestis even; whencountis even,countitself is divisible by2. Either way, integer division// 2is always exact!Finally, we cap
customers_to_serve = min(m, total_stock)up front and bill the remainingcustomers_to_serve - units_sold_abovebuyerscutoff_priceeach:def maximize_revenue(n: int, quantity: List[int], m: int) -> int: # Phase 1: Handle empty inventory or zero customers up front, and cap sales # at total_stock because extra customers beyond available stock buy nothing. if not quantity or m <= 0: return 0 total_stock = sum(quantity) if total_stock == 0: return 0 customers_to_serve = min(m, total_stock) # Phase 2: Binary search for the horizontal price threshold where full-band # selling stops. Every unit priced > cutoff_price will be sold completely. cutoff_price = find_cutoff_price(quantity, customers_to_serve) # Phase 3: Sum the revenue of all units priced strictly above cutoff_price. total_revenue = 0 units_sold_above = 0 for stock in quantity: if stock > cutoff_price: # Prices sold from this product run from (cutoff_price + 1) up to stock. lowest_price_sold = cutoff_price + 1 highest_price_sold = stock count_sold = stock - cutoff_price # Arithmetic series sum: (first_term + last_term) * num_terms // 2. # Either (lowest + highest) or count_sold is always even, so // 2 is exact. product_revenue = (lowest_price_sold + highest_price_sold) * count_sold // 2 total_revenue += product_revenue units_sold_above += count_sold # Phase 4: Every remaining served customer buys one unit priced at cutoff_price. # By minimal choice of cutoff_price, enough products have stock >= cutoff_price. remaining_customers = customers_to_serve - units_sold_above total_revenue += remaining_customers * cutoff_price return total_revenueTrace Example 3 and Example 4
Example 3: quantity = [8, 8, 8], m = 5 - total_stock = 24 -> customers_to_serve = min(5, 24) = 5 - Binary search on [0, 8]: mid = 4 -> count_units_above(4) = 12 > 5 -> low = 5 mid = 6 -> count_units_above(6) = 6 > 5 -> low = 7 mid = 7 -> count_units_above(7) = 3 <= 5 -> high = 7 Stops at cutoff_price = 7. - Units strictly above 7: each of the 3 categories sells price 8 units_sold_above = 3, total_revenue = 3 * 8 = 24 - Remaining buyers: 5 - 3 = 2 buyers each pay cutoff_price = 7 total_revenue = 24 + 2 * 7 = 38. Example 4: quantity = [2, 0, 4], m = 9 - total_stock = 6 -> customers_to_serve = min(9, 6) = 6 - Binary search on [0, 4]: count_units_above(0) = 6 <= 6 -> stops at cutoff_price = 0. - Units strictly above 0: category 0 (stock 2): (1 + 2) * 2 // 2 = 3 category 1 (stock 0): skipped (0 <= 0) category 2 (stock 4): (1 + 4) * 4 // 2 = 10 units_sold_above = 6, total_revenue = 13 - Remaining buyers: 6 - 6 = 0 -> returns 13.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_units_above(quantity: List[int], cutoff_price: int) -> int: """Count total units across all products priced strictly above cutoff_price.""" total_above = 0 for stock in quantity: if stock > cutoff_price: # A product with `stock` units offers prices stock, stock - 1, ..., 1, # so exactly (stock - cutoff_price) of its units cost > cutoff_price. total_above += stock - cutoff_price return total_above def find_cutoff_price(quantity: List[int], customers_to_serve: int) -> int: """Return the smallest price t >= 0 with at most customers_to_serve units above t.""" # Search range [low, high]: # high = max(quantity) always works because 0 units are priced above max(quantity). low = 0 high = max(quantity) while low < high: mid = (low + high) // 2 # As mid increases, count_units_above(mid) only decreases or stays equal. if count_units_above(quantity, mid) <= customers_to_serve: # mid has <= customers_to_serve units above it, so the smallest valid # cutoff is at or below mid; keep mid inside the search interval. high = mid else: # Strictly more than customers_to_serve units sit above mid, # so mid is too low and cannot be the cutoff. low = mid + 1 return low def maximize_revenue(n: int, quantity: List[int], m: int) -> int: # Phase 1: Handle empty inventory or zero customers up front, and cap sales # at total_stock because extra customers beyond available stock buy nothing. if not quantity or m <= 0: return 0 total_stock = sum(quantity) if total_stock == 0: return 0 customers_to_serve = min(m, total_stock) # Phase 2: Binary search for the horizontal price threshold where full-band # selling stops. Every unit priced > cutoff_price will be sold completely. cutoff_price = find_cutoff_price(quantity, customers_to_serve) # Phase 3: Sum the revenue of all units priced strictly above cutoff_price. total_revenue = 0 units_sold_above = 0 for stock in quantity: if stock > cutoff_price: # Prices sold from this product run from (cutoff_price + 1) up to stock. lowest_price_sold = cutoff_price + 1 highest_price_sold = stock count_sold = stock - cutoff_price # Arithmetic series sum: (first_term + last_term) * num_terms // 2. # Either (lowest + highest) or count_sold is always even, so // 2 is exact. product_revenue = (lowest_price_sold + highest_price_sold) * count_sold // 2 total_revenue += product_revenue units_sold_above += count_sold # Phase 4: Every remaining served customer buys one unit priced at cutoff_price. # By minimal choice of cutoff_price, enough products have stock >= cutoff_price. remaining_customers = customers_to_serve - units_sold_above total_revenue += remaining_customers * cutoff_price return total_revenue✅ Submit now — all tests should pass.
Intuition & how it works
Imagine each category's inventory as a vertical stack of numbered price tags counting down from quantity[i] at the top to 1 at the bottom. To earn the most revenue across m buyers, we always want to peel off whichever stack currently has the highest top tag—so across m sales, we collect the m largest price tags in the entire warehouse. Rather than peeling tags one buyer at a time, imagine lowering a horizontal ruler from the tallest stack downward until m or fewer tags sit strictly above the ruler: we sum every tag above the ruler in bulk using an arithmetic series (a sum of evenly spaced numbers like 4 + 5 + 6 computed in one multiplication), and serve any remaining buyers using tags sitting right on the ruler line.
Simulating sales one buyer at a time—even using a max-heap (a tree-based priority queue that extracts and updates the largest stock in O(log n) time)—takes O(m log n) steps. When m and stock counts reach 10^9, a billion heap updates time out. Finding the ruler height with binary search—repeatedly halving the [0, max(quantity)] price range using a monotonic (never-increasing) count of units above mid—finishes in ~30 fast passes over quantity, regardless of how large m is.
Walk through Example 2 (quantity = [6, 2, 5], m = 4):
- Total stock is 6 + 2 + 5 = 13, so customers_to_serve = min(4, 13) = 4, and we binary search cutoff_price in [0, 6].
- At mid = 3, count_units_above(3) = (6 - 3) + 0 + (5 - 3) = 5 > 4 (too many units above 3), so we raise low to 4.
- At mid = 4, count_units_above(4) = (6 - 4) + 0 + (5 - 4) = 3 <= 4, and 4 is the smallest threshold with <= 4 units above it, so cutoff_price = 4.
- Selling everything strictly above 4 collects 6 + 5 = 11 from category 0 (2 units) and 5 from category 2 (1 unit), totaling 16 across 3 units, and the 4 - 3 = 1 remaining buyer pays cutoff_price = 4 for 20 total.
Complexity
Let n = len(quantity) be the number of categories and Q = max(quantity) be the largest initial stock.
- Time:
O(n log Q). Summing and finding the maximum stock each scan thencategories once (O(n)), the binary search halves[0, Q]at mostceil(log2(Q + 1))times (~30 iterations forQ = 10^9) while doing anO(n)pass incount_units_aboveeach iteration, and the final revenue loop scans thencategories one last time. Crucially, the runtime is independent ofm. - Space:
O(1)auxiliary space. Only a handful of scalar integer variables (low,high,mid,total_revenue,units_sold_above) are allocated beyond the input list.
Edge cases
- Zero buyers (
m = 0): handled immediately at the start and returns0. - All stocks are
0orquantityis empty:total_stock == 0returns0beforemax(quantity)is called. - More buyers than total stock (
m > sum(quantity)):customers_to_serveis capped attotal_stock,cutoff_pricelands on0, every unit from1..stockis sold, and unserved buyers contribute0(as in Example 4). - Ties at the cutoff price (
quantity = [8, 8, 8],m = 5):cutoff_price = 7;3units sell at price8(units_sold_above = 3), and5 - 3 = 2buyers take two of the7-priced units—returning38. - 64-bit / big-integer totals (
quantity = [10^9],m = 10^9): total revenue reaches~5 × 10^17. Pythonintexpands automatically without overflow; in C++ or Java you would needlong long/long(and 128-bit care before dividing(lowest + highest) * countby2if stocks exceed3 × 10^9).
Common mistakes
- Simulating buyer by buyer with a heap: passes small tests, but
O(m log n)times out whenm = 10^9. - Picking the
mlargest categories instead of themlargest unit prices: onquantity = [4, 1], m = 3, selling three times from category0(4 + 3 + 2 = 9) beats touching category1(4 + 3 + 1 = 8). - Off-by-one in the arithmetic series: selling prices strictly above
tmeans sellingt + 1, t + 2, ..., stock, which hasstock - tterms starting att + 1—notstock - t + 1terms starting att. - Charging remaining buyers
cutoff_price + 1orcutoff_price - 1: all units atcutoff_price + 1and above were already counted inunits_sold_above, so the tie-breaking partial band sits right atcutoff_price. - Not capping
m(or starting binary search atlow = 1): iflowstarts at1without cappingmatsum(quantity), unserved buyers when stock runs out get billed1each instead of0.
Alternative approaches
- Sort descending and sweep level bands: Sort
quantityfrom largest to smallest (O(n log n)), then flatten the current tied tallest stocks down to the next distinct stock height in rectangular bands usingdivmodon remainingm. Runs inO(n log n)time independent ofmax(quantity), though indexing band widths and the partial final row is easier to get off by one than binary search. - Max-heap simulation: Push negated stocks into Python's
heapqand pop/decrementmin(m, sum(quantity))times inO(n + m log n)time. Suitable only whenmis guaranteed small (m <= 10^5) or as an oracle in tests.
Follow-up questions
- How could you preprocess
quantityonce to answer many independent queries with differentmvalues quickly? Sortquantityonce in ascending order and build a prefix sum array (whereprefix[k]stores the sum of the firstksorted stocks) plus a prefix sum ofstock * (stock + 1) // 2inO(n log n)preprocessing time. For any candidate thresholdt, locating the first index withstock > tvia binary search on the sorted array lets you evaluate bothcount_units_above(t)and the series revenue inO(1)time from suffix sums, answering eachmquery inO(log n · log Q)time. - How would you return the exact number of units sold from each category in addition to the maximum revenue? After finding
cutoff_price, start by settingsold[i] = max(0, quantity[i] - cutoff_price)for each categoryi. Whencutoff_price > 0, scani = 0 .. n - 1and add1more unit to the firstcustomers_to_serve - sum(sold)categories satisfyingquantity[i] >= cutoff_price—this takesO(n)time and outputs a compactO(n)schedule even whenm = 10^9. - What changes if category
ichargesweight[i] * kinstead ofkwhenkunits remain? Assuming positive integer weightsweight[i], each category's unit pricesweight[i] * quantity[i], ..., weight[i] * 1still decrease monotonically from top to bottom, so the horizontal price-threshold method carries right over! Categoryicontributesmax(0, quantity[i] - price // weight[i])units strictly aboveprice, so binary searchingpriceover[0, max(weight[i] * quantity[i])]and summingweight[i]times each category's integer series solves it inO(n log(max(weight * quantity)))time.
Follow-up questions
- How could you preprocess `quantity` once to answer many independent queries with different `m` values quickly?
- How would you return the exact number of units sold from each category in addition to the maximum revenue?
- What changes if category `i` charges `weight[i] * k` instead of `k` when `k` units remain?
Similar questions
- Replay Guarded Key-Value Store Commands
- Maximum Drawdown in a Cumulative PnL Series
- Even-Product Triplets Under a Modulus
- Counting Staircase Sequences With Custom Jumps
- Equalizing an Array via All-Except-One Increments
- Cross-Array Target Sum in Two Sorted Lists
More Squarepoint interview questions
- Replay Guarded Key-Value Store Commands Easy
- Fixed-Buffer Circular Queue vs Linked-Node Storage Medium
- Contrasting Bonds, Common Stock, and Dividend Policy Medium Pro
- First-Drawer Win Probability With Tied-Rank Reshuffles Medium Pro
- Compile-Time Merging of C++ Index Sequences Medium Pro
- Safe Regular-File Counting Across Arbitrary Paths Medium Pro
- Even-Product Triplets Under a Modulus Medium Pro
- Counting Staircase Sequences With Custom Jumps Medium Pro
- Sorted Contiguous Container With Move Semantics Medium Pro
- OLS Market Beta From Paired Return Series Medium Pro