Sell Diminishing-Valued Colored Balls - Problem

You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.

The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).

You are given an integer array inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.

Return the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: inventory = [2,5], orders = 4
Output: 14
💡 Note: Sell balls with values 5, 4, 3, 2. Total = 5+4+3+2 = 14. We sell from color 1 (value 5), then 4, then 3, then from color 0 (value 2).
Example 2 — Multiple Colors
$ Input: inventory = [3,5], orders = 6
Output: 19
💡 Note: Sell balls with values 5, 4, 3, 3, 2, 1. Total = 5+4+3+3+2+1 = 18. Wait, let me recalculate: 5+4+3+3+2+1 = 18. Actually: 5+4+3+3+2+2 = 19.
Example 3 — Large Numbers
$ Input: inventory = [1000000000], orders = 1000000000
Output: 21
💡 Note: This would result in a very large number, so we return it modulo 10^9 + 7.

Constraints

  • 1 ≤ inventory.length ≤ 105
  • 1 ≤ inventory[i] ≤ 109
  • 1 ≤ orders ≤ min(sum(inventory[i]), 109)

Visualization

Tap to expand
Sell Diminishing-Valued Colored BallsInitial InventoryColor 02 ballsColor 15 ballsSelling Process (orders=4)5432Sell highest value firstRevenue CalculationBall 1: Value = 5Ball 2: Value = 4Ball 3: Value = 3Ball 4: Value = 2Greedy Strategy: Always sell the most valuable ball availableMaximum Revenue: 5 + 4 + 3 + 2 = 14
Understanding the Visualization
1
Input
inventory=[2,5], orders=4 - we have 2 balls of color 0 and 5 balls of color 1
2
Greedy Strategy
Always sell from the color with highest current value
3
Output
Maximum revenue = 14 by selling balls with values 5,4,3,2
Key Takeaway
🎯 Key Insight: Use greedy approach - always sell the most valuable ball first to maximize revenue
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.6K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen