|
| 1 | +/** |
| 2 | + * 1648. Sell Diminishing-Valued Colored Balls |
| 3 | + * https://leetcode.com/problems/sell-diminishing-valued-colored-balls/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have an inventory of different colored balls, and there is a customer that wants orders |
| 7 | + * balls of any color. |
| 8 | + * |
| 9 | + * The customer weirdly values the colored balls. Each colored ball's value is the number of balls |
| 10 | + * of that color you currently have in your inventory. For example, if you own 6 yellow balls, |
| 11 | + * the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 |
| 12 | + * yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls |
| 13 | + * decreases as you sell more to the customer). |
| 14 | + * |
| 15 | + * You are given an integer array, inventory, where inventory[i] represents the number of balls of |
| 16 | + * the ith color that you initially own. You are also given an integer orders, which represents |
| 17 | + * the total number of balls that the customer wants. You can sell the balls in any order. |
| 18 | + * |
| 19 | + * Return the maximum total value that you can attain after selling orders colored balls. As the |
| 20 | + * answer may be too large, return it modulo 109 + 7. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[]} inventory |
| 25 | + * @param {number} orders |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var maxProfit = function(inventory, orders) { |
| 29 | + const MOD = 1e9 + 7; |
| 30 | + inventory.sort((a, b) => b - a); |
| 31 | + inventory.push(0); |
| 32 | + |
| 33 | + let totalProfit = 0; |
| 34 | + let currentColor = 0; |
| 35 | + let ballsSold = 0; |
| 36 | + |
| 37 | + while (ballsSold < orders) { |
| 38 | + const currentCount = inventory[currentColor]; |
| 39 | + const nextCount = inventory[currentColor + 1]; |
| 40 | + const colors = currentColor + 1; |
| 41 | + const ballsToSell = Math.min( |
| 42 | + orders - ballsSold, |
| 43 | + colors * (currentCount - nextCount) |
| 44 | + ); |
| 45 | + |
| 46 | + const fullSets = Math.floor(ballsToSell / colors); |
| 47 | + const remainder = ballsToSell % colors; |
| 48 | + |
| 49 | + if (fullSets > 0) { |
| 50 | + const endValue = currentCount - fullSets + 1; |
| 51 | + let sequenceSum = (BigInt(colors) * BigInt(fullSets) % BigInt(MOD)) |
| 52 | + * (BigInt(currentCount) + BigInt(endValue)) % BigInt(MOD); |
| 53 | + sequenceSum = (sequenceSum * BigInt(500000004)) % BigInt(MOD); |
| 54 | + totalProfit = (totalProfit + Number(sequenceSum)) % MOD; |
| 55 | + } |
| 56 | + |
| 57 | + if (remainder > 0) { |
| 58 | + totalProfit = (totalProfit + (remainder * (currentCount - fullSets)) % MOD) % MOD; |
| 59 | + } |
| 60 | + |
| 61 | + ballsSold += ballsToSell; |
| 62 | + currentColor++; |
| 63 | + } |
| 64 | + |
| 65 | + return totalProfit; |
| 66 | +}; |
0 commit comments