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 i when k units of category i are currently left collects k in revenue and reduces category i's remaining stock to k - 1.
  • Categories with 0 remaining units cannot be sold.
  • When m exceeds the combined initial stock across all n categories, every unit in the warehouse is sold and the leftover m - sum(quantity) buyers purchase nothing (0 revenue).

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^5
  • len(quantity) == n
  • 0 <= quantity[i] <= 10^9
  • 0 <= m <= 10^14

Step-by-step walkthrough

  1. Picture each category's stock as a stack of price tags

    Category i starts with quantity[i] units. Because a buyer pays the current remaining count before quantity[i] shrinks by 1, selling units from a category with initial count q collects q, then q - 1, then q - 2, down to 1.

    You can picture each category as a vertical stack of price tags sorted from quantity[i] on top down to 1 at 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 m buyers, one unit each. Whenever m exceeds the combined stock across all categories, every available unit is sold and the leftover buyers pay 0.

  2. 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 m sales can earn more than the sum of the m largest 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 m times is therefore guaranteed to collect the m highest 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)—takes O(m log n) steps. When m and quantity[i] reach 10^9, a billion heap operations time out. We need to sum entire bands of sales at once.

  3. Key insight: slice all stacks horizontally with one cutoff price

    Inspect the 4 largest price tags in Example 2 (quantity = [6, 2, 5], m = 4): they are 6, 5, 5, and one of the 4s. Draw a horizontal line at cutoff_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 above cutoff_price is sold (stock - cutoff_price units from each category with stock > cutoff_price). 2. Whatever buyers remain (customers_to_serve - units_sold_above) each buy one unit priced at cutoff_price.

    How do we find cutoff_price? Let count_units_above(t) be the total number of units priced strictly greater than t. As t rises from 0 to max(quantity), count_units_above(t) shrinks monotonically (never increases) from total_stock down to 0:

    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 t
    

    Because the no / YES transition is monotonic, binary search locates the smallest valid cutoff_price in at most ~30 steps (log2(10^9) ≈ 30)!

    Why are there always enough units priced at cutoff_price for the remaining buyers? - If cutoff_price == 0, then count_units_above(0) == total_stock == customers_to_serve, so 0 buyers remain. - If cutoff_price >= 1, then cutoff_price - 1 failed the <= customers_to_serve test, meaning count_units_above(cutoff_price - 1) > customers_to_serve. The gap count_units_above(cutoff_price - 1) - count_units_above(cutoff_price) equals the exact number of units priced at cutoff_price, guaranteeing enough tied units to serve every remaining buyer!

  4. Code the helper and binary search

    First we write count_units_above, then find_cutoff_price over [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 low
    
  5. Sum each category's sold band with the arithmetic series formula

    Once we know cutoff_price, each category with stock > cutoff_price sells all consecutive prices from cutoff_price + 1 through stock.

    Instead of looping over those prices one by one, we apply the arithmetic series formula—the sum of consecutive integers from first to last across count = last - first + 1 terms 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 = 15
    

    Notice that when count is odd, lowest and highest share the same parity so lowest + highest is even; when count is even, count itself is divisible by 2. Either way, integer division // 2 is always exact!

    Finally, we cap customers_to_serve = min(m, total_stock) up front and bill the remaining customers_to_serve - units_sold_above buyers cutoff_price each:

    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
    
  6. Trace 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.
    
  7. 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 the n categories once (O(n)), the binary search halves [0, Q] at most ceil(log2(Q + 1)) times (~30 iterations for Q = 10^9) while doing an O(n) pass in count_units_above each iteration, and the final revenue loop scans the n categories one last time. Crucially, the runtime is independent of m.
  • 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 returns 0.
  • All stocks are 0 or quantity is empty: total_stock == 0 returns 0 before max(quantity) is called.
  • More buyers than total stock (m > sum(quantity)): customers_to_serve is capped at total_stock, cutoff_price lands on 0, every unit from 1..stock is sold, and unserved buyers contribute 0 (as in Example 4).
  • Ties at the cutoff price (quantity = [8, 8, 8], m = 5): cutoff_price = 7; 3 units sell at price 8 (units_sold_above = 3), and 5 - 3 = 2 buyers take two of the 7-priced units—returning 38.
  • 64-bit / big-integer totals (quantity = [10^9], m = 10^9): total revenue reaches ~5 × 10^17. Python int expands automatically without overflow; in C++ or Java you would need long long / long (and 128-bit care before dividing (lowest + highest) * count by 2 if stocks exceed 3 × 10^9).

Common mistakes

  • Simulating buyer by buyer with a heap: passes small tests, but O(m log n) times out when m = 10^9.
  • Picking the m largest categories instead of the m largest unit prices: on quantity = [4, 1], m = 3, selling three times from category 0 (4 + 3 + 2 = 9) beats touching category 1 (4 + 3 + 1 = 8).
  • Off-by-one in the arithmetic series: selling prices strictly above t means selling t + 1, t + 2, ..., stock, which has stock - t terms starting at t + 1—not stock - t + 1 terms starting at t.
  • Charging remaining buyers cutoff_price + 1 or cutoff_price - 1: all units at cutoff_price + 1 and above were already counted in units_sold_above, so the tie-breaking partial band sits right at cutoff_price.
  • Not capping m (or starting binary search at low = 1): if low starts at 1 without capping m at sum(quantity), unserved buyers when stock runs out get billed 1 each instead of 0.

Alternative approaches

  • Sort descending and sweep level bands: Sort quantity from largest to smallest (O(n log n)), then flatten the current tied tallest stocks down to the next distinct stock height in rectangular bands using divmod on remaining m. Runs in O(n log n) time independent of max(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 heapq and pop/decrement min(m, sum(quantity)) times in O(n + m log n) time. Suitable only when m is guaranteed small (m <= 10^5) or as an oracle in tests.

Follow-up questions

  • How could you preprocess quantity once to answer many independent queries with different m values quickly? Sort quantity once in ascending order and build a prefix sum array (where prefix[k] stores the sum of the first k sorted stocks) plus a prefix sum of stock * (stock + 1) // 2 in O(n log n) preprocessing time. For any candidate threshold t, locating the first index with stock > t via binary search on the sorted array lets you evaluate both count_units_above(t) and the series revenue in O(1) time from suffix sums, answering each m query in O(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 setting sold[i] = max(0, quantity[i] - cutoff_price) for each category i. When cutoff_price > 0, scan i = 0 .. n - 1 and add 1 more unit to the first customers_to_serve - sum(sold) categories satisfying quantity[i] >= cutoff_price—this takes O(n) time and outputs a compact O(n) schedule even when m = 10^9.
  • What changes if category i charges weight[i] * k instead of k when k units remain? Assuming positive integer weights weight[i], each category's unit prices weight[i] * quantity[i], ..., weight[i] * 1 still decrease monotonically from top to bottom, so the horizontal price-threshold method carries right over! Category i contributes max(0, quantity[i] - price // weight[i]) units strictly above price, so binary searching price over [0, max(weight[i] * quantity[i])] and summing weight[i] times each category's integer series solves it in O(n log(max(weight * quantity))) time.

Follow-up questions

Similar questions

More Squarepoint interview questions

All 38 Squarepoint questions →