KatInterview

Optimal Order Fulfillment with Decaying Prices

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbinary-searchgreedymath

Last 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 stock where stock[i] represents the initial quantity available for type i
  • An integer numOrders representing 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 type
  • numOrders: Positive integer for total orders to fill

Output Format

Return a single integer representing the maximum possible revenue.

Constraints

  • 1 <= len(stock) <= 10^5
  • 1 <= stock[i] <= 10^9
  • 1 <= 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.