Optimal Order Fulfillment with Decaying Prices
Heaps, Sorting & SearchModel answerLast updated
Determine the maximum revenue when fulfilling orders from inventory where each item's price equals its current stock level and decreases with each sale.
Problem Description
You're operating a rental service with multiple item types. For each type, you maintain a certain quantity in stock. The pricing model works as follows: when you rent an item of a particular type, the revenue equals the current stock count for that type, and then the stock decreases by one.
You're given:
- An array
stockwherestock[i]represents the initial quantity available for typei - An integer
numOrdersrepresenting how many total items you need to fulfill
Your task is to determine the maximum total revenue achievable by optimally choosing which types to fulfill orders from.
Input Format
stock: List of positive integers representing initial quantities per typenumOrders: Positive integer for total orders to fill
Output Format
Return a single integer representing the maximum possible revenue.
Constraints
1 <= len(stock) <= 10^51 <= stock[i] <= 10^91 <= numOrders <= sum(stock)
Examples
Example 1:
Input: stock = [2, 5], numOrders = 4
Output: 14
Explanation: Fulfill in this sequence:
- From type 2 (stock=5): earn 5, now [2, 4]
- From type 2 (stock=4): earn 4, now [2, 3]
- From type 2 (stock=3): earn 3, now [2, 2]
- From type 1 (stock=2): earn 2, now [1, 2] Total: 5 + 4 + 3 + 2 = 14
Example 2:
Input: stock = [3, 5], numOrders = 6
Output: 19
Explanation: The six highest prices are 5, 4, 3, 3, 2, 2, yielding 19.
Example 3:
Input: stock = [1000000000], numOrders = 1000000000
Output: 500000000500000000
Hints
Hint 1
A greedy approach of always taking from the type with the highest current stock is optimal, but simulating each individual order is too slow for large inputs.
Hint 2
Think about which price levels will be completely exhausted versus partially used. There's a threshold price where you transition from selling all units above it to selling only some units at it.
Hint 3
Binary search can help you find this threshold price efficiently. Once found, you can calculate revenue using arithmetic series formulas rather than simulating individual sales.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
Core Insight
The optimal strategy is greedy: always fulfill the next order from whichever type currently has the highest stock, since that yields the highest immediate revenue. However, simulating this order-by-order would require O(numOrders × log N) time with a heap, which is prohibitively expensive when numOrders can approach 10^14.
The key optimization is recognizing that this greedy process "levels" the inventory: we drain the tallest stocks down until they match the next-tallest, then drain multiple types together. We can identify a threshold level and use closed-form arithmetic to compute the result.
The Threshold Concept
After fulfilling all orders, there exists some threshold value T such that:
- Every type that started above
Thas been reduced to exactlyT(all units priced aboveTwere sold) - Some number of remaining orders (fewer than the count of types at level
≥ T) were sold at price exactlyT
We can binary search for this threshold.
Algorithm Steps
-
Binary search for the threshold
T:- Define
units_above(t)= total units priced strictly abovet - Find the smallest
Twhereunits_above(T) ≤ numOrders
- Define
-
Calculate revenue from complete levels:
- For each type with initial stock
s > T, we sold all units priced(T+1)throughs - This is an arithmetic series:
(T+1) + (T+2) + ... + s = (s + T + 1) × (s - T) / 2
- For each type with initial stock
-
Handle remainder:
- Let
remaining = numOrders - units_above(T) - These
remainingorders are fulfilled at priceTeach - Add
remaining × Tto the total
- Let
Correctness
Why greedy works: If we sell a unit at price p while a unit priced q > p remains unsold, swapping them increases revenue. Therefore, the optimal solution always sells the numOrders highest-priced units from the combined pool.
Why the threshold captures this: The threshold approach ensures we take exactly the top numOrders prices by exhausting all prices above T first, then partially taking from level T.
Complexity Analysis
-
Time: O(N log M) where N is the number of types and M is the maximum stock value
- Binary search runs O(log M) iterations
- Each iteration scans all N types
- With M ≤ 10^9, this is roughly 30 × N operations
-
Space: O(1) auxiliary space
This is vastly better than heap simulation's O(numOrders × log N), which would be infeasible.
Implementation
from typing import List
def maxProfit(stock: List[int], numOrders: int) -> int:
def count_above(threshold: int) -> int:
"""Count units priced strictly above threshold."""
return sum(max(0, s - threshold) for s in stock)
# Binary search for the threshold level
left, right = 0, max(stock)
while left < right:
mid = (left + right) // 2
if count_above(mid) <= numOrders:
right = mid
else:
left = mid + 1
threshold = left
revenue = 0
fulfilled = 0
# Sum arithmetic series for each type above threshold
for s in stock:
if s > threshold:
count = s - threshold
fulfilled += count
# Series sum: (T+1) + (T+2) + ... + s
revenue += (s + threshold + 1) * count // 2
# Remaining orders at price threshold
remaining = numOrders - fulfilled
revenue += remaining * threshold
return revenue
Example Walkthrough
For stock = [2, 5], numOrders = 4:
-
Binary search finds
T = 2:count_above(2) = (5-2) = 3 ≤ 4✓count_above(1) = (2-1) + (5-1) = 5 > 4✗
-
Type with stock 5: sell prices 3, 4, 5
- Series: (5 + 3) × 3 / 2 = 12
- Fulfilled: 3 orders
-
Remaining: 4 - 3 = 1 order at price 2
- Add: 1 × 2 = 2
-
Total: 12 + 2 = 14
Common Mistakes
- Off-by-one in threshold logic: Confusing "above T" vs "at least T" leads to incorrect counts
- Integer division order: Computing
(a + b) * c / 2can overflow; ensure division is safe - Not handling remainder correctly: Forgetting that some orders happen exactly at the threshold
- Using simulation: O(numOrders) approaches timeout on large inputs
- Overflow: In languages without arbitrary precision, the result can exceed 64-bit integers (use modular arithmetic if required)
Edge Cases
- Single type: Reduces to simple arithmetic series from
sdown tos - numOrders + 1 - All orders exhaust inventory: Threshold becomes 0, remainder is 0
- Multiple types with equal stock: Remainder gets distributed among ties at the threshold level
- Very large values: Result can exceed 10^22; Python handles this natively