Imagine you're running a unique toy store where colored balls have a peculiar pricing system - each ball's value equals the current remaining inventory count of that color!
๐ฏ The Challenge: You have an inventory array where inventory[i] represents the number of balls of the i-th color. A customer wants to buy exactly orders balls total, and you need to maximize your revenue.
How the pricing works:
- If you have 6 yellow balls, the first yellow ball sells for 6
- After selling it, you have 5 yellow balls left, so the next yellow ball sells for 5
- The value keeps decreasing as inventory depletes
You can sell balls in any order you want. Return the maximum total revenue modulo 109 + 7.
Example: With inventory [2,5] and orders = 4:
Optimal strategy: Sell balls valued at 5, 4, 3, 2 โ Total revenue = 14
Input & Output
Visualization
Time & Space Complexity
O(n log n) for sorting, O(n log(max_inventory)) for binary search with O(n) validation
Only using constant extra space after sorting in place
Constraints
- 1 โค inventory.length โค 105
- 1 โค inventory[i] โค 109
- 1 โค orders โค min(2ร109, sum(inventory[i]))
- Answer must be returned modulo 109 + 7