Sell Diminishing-Valued Colored Balls

Medium

Description

You have an inventory of colored balls to sell. The value of a ball is its inventory count. You want to sell exactly n balls. Return the maximum total value that you can attain after selling n balls.

Examples

Input:inventory = [2,5], orders = 4
Output:14
Explanation:

Sell 5,4,3,2 = 14.

Input:inventory = [3,5,1], orders = 6
Output:27
Explanation:

Selling from highest value first: sell the ball worth 5, then 4, then two balls worth 3 (from inventories [3,3,1]), then two worth 2, giving 5+4+3+3+2+2 = 19. The optimal greedy selection of 6 balls yields 27.

Input:inventory = [1000000], orders = 3
Output:2999997
Explanation:

There are one type of ball with inventory count 1000000. Selling 3 balls with values 1000000, 999999, and 999998. Total: 1000000 + 999999 + 999998 = 2999997.

Constraints

  • 1 ≤ inventory.length ≤ 10^5
  • 1 ≤ orders ≤ min(sum(inventory), 10^9)

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!