[LeetCode] Sell Diminishing-Valued Colored Balls

1648. Sell Diminishing-Valued Colored Balls

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
private:
const int MOD = 1000000007;

public:
int maxProfit(vector<int>& inventory, int orders) {
long long res = 0;
sort(inventory.begin(), inventory.end());
int n = lower_bound(inventory.begin(), inventory.end(), inventory.back()) - inventory.begin();

while(orders) {
int mul = inventory.size() - n;
if(n && (inventory[n] - inventory[n - 1]) * mul <= orders) {
long long diff = inventory[n] - inventory[n - 1];
orders -= diff * mul;
res += mul * diff * (2 * inventory[n] - diff + 1)>>1;
--n;
while(n && inventory[n - 1] == inventory[n])
--n;
} else {
long long diff = orders / mul;
res += (mul * diff * (2 * inventory[n] - diff + 1)>>1) + (inventory[n] - diff) * (orders % mul);
return res % MOD;
}
res %= MOD;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/05/PS/LeetCode/sell-diminishing-valued-colored-balls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.