Sell Diminishing-Valued Colored Balls
Sell Diminishing-Valued Colored Balls is a medium binary search problem solved with the binary search on answer space pattern.
The best approach, optimal (binary search on the threshold), runs in O(n log M) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from max-heap, one ball at a time up.
Problem
A shop holds balls of several colours. You are given an integer array inventory, where inventory[i] is how many balls of colour i the shop has, and an integer orders, the total number of balls a customer wants to buy. The colours of the balls sold can be any mix you like.
The price of a ball depends on how many balls of its colour are still in stock at the moment of the sale: if the shop holds k balls of that colour, the ball sells for k. After the sale the shop holds k - 1 of them, so the next ball of the same colour is worth one less.
Choose which balls to sell so that exactly orders balls are sold and the total money earned is as large as possible. The total can be huge, so return it modulo 10^9 + 7.
Examples
Example 1
- Input
inventory = [4,6], orders = 5- Output
22- Why
- Sell the second colour while it is the richer one: 6, then 5. Both colours now hold 4 balls, so sell one of each for 4 + 4. The last sale is worth 3. The total is 6 + 5 + 4 + 4 + 3 = 22.
Example 2
- Input
inventory = [3,9,5], orders = 10- Output
54- Why
- The colour with 9 balls sells 9, 8, 7 and 6 and is left with 5, level with the third colour. Those two sell 5, 5 and then 4, 4, after which all three colours hold 3. Two more sales at 3 finish the order: 9 + 8 + 7 + 6 + 5 + 5 + 4 + 4 + 3 + 3 = 54.
Example 3
- Input
inventory = [1,1,1], orders = 3- Output
3- Why
- Every ball is the only one of its colour, so each sale is worth 1, and all three are sold.
Constraints
1 <= inventory.length <= 10^51 <= inventory[i] <= 10^91 <= orders <= min(sum(inventory), 10^9)- Return the answer modulo
10^9 + 7.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Max-heap, one ball at a time | O(n + orders · log n) | O(n) |
| Sort and sell level by level | O(n log n) | O(n) |
| Optimal (binary search on the threshold) | O(n log M) | O(1) |
1Max-heap, one ball at a time
O(n + orders · log n)Building the heap is O(n); each of the orders sales is one pop and one push.O(n)The heap holds one entry per colour.The greedy rule is simple: every sale should take a ball of the colour that currently has the most balls, because that sale is worth the most and taking it now never lowers what the other sales can earn. Keep all counts in a max-heap. For each of the orders, pop the largest count, add it to the total, and push it back one smaller. Correct, but it does one heap operation per sale, which is far too slow when orders is near a billion.
- Push every inventory count into a max-heap.
- Repeat orders times: pop the top value, add it to the total modulo 10^9 + 7, and push top - 1 back if it is still positive.
- Return the total.
class Solution {
public int maxProfit(int[] inventory, int orders) {
final long MOD = 1_000_000_007L;
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int x : inventory) heap.offer(x);
long total = 0;
for (int k = 0; k < orders; k++) {
int top = heap.poll();
total = (total + top) % MOD;
if (top > 1) heap.offer(top - 1);
}
return (int) total;
}
}class Solution:
def maxProfit(self, inventory: List[int], orders: int) -> int:
MOD = 10**9 + 7
heap = [-x for x in inventory]
heapq.heapify(heap)
total = 0
for _ in range(orders):
top = -heapq.heappop(heap)
total = (total + top) % MOD
if top > 1:
heapq.heappush(heap, -(top - 1))
return totalclass Solution {
public:
int maxProfit(vector<int>& inventory, int orders) {
const long long MOD = 1000000007LL;
priority_queue<int> heap(inventory.begin(), inventory.end());
long long total = 0;
for (int k = 0; k < orders; k++) {
int top = heap.top();
heap.pop();
total = (total + top) % MOD;
if (top > 1) heap.push(top - 1);
}
return (int)total;
}
};function maxProfit(inventory, orders) {
const MOD = 1000000007;
const heap = [];
for (const x of inventory) push(x);
let total = 0;
for (let k = 0; k < orders; k++) {
const top = pop();
total = (total + top) % MOD;
if (top > 1) push(top - 1);
}
return total;
// a small binary max-heap, since JavaScript has none built in
function push(x) {
heap.push(x);
let i = heap.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p] >= heap[i]) break;
[heap[p], heap[i]] = [heap[i], heap[p]];
i = p;
}
}
function pop() {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < heap.length && heap[l] > heap[m]) m = l;
if (r < heap.length && heap[r] > heap[m]) m = r;
if (m === i) break;
[heap[m], heap[i]] = [heap[i], heap[m]];
i = m;
}
}
return top;
}
}2Sort and sell level by level
O(n log n)Sorting dominates; the walk down the sorted counts is a single pass with O(1) work per colour.O(n)The sorted copy of inventory.Sort the counts and work from the tallest down. Keep width, the number of colours that are currently tied at the top. Between the current top height cur and the next distinct height next, there are cur - next levels, each one made of width balls of the same value. If the remaining orders cover all of those levels, sell them in one go with the formula for a run of consecutive values, multiplied by width. Otherwise sell as many full levels as fit, full = left / width, and then left % width single balls at the value just below them, and stop.
- Sort a copy of inventory. Walk i from the largest index down, adding one to width each time.
- cur = inv[i], next = inv[i - 1] (or 0 for the last one). If they are equal, keep going so width grows.
- If width · (cur - next) <= left, add width · (next + 1 + ... + cur) and subtract those sales from left.
- Otherwise full = left / width, rem = left % width: add width · (cur - full + 1 + ... + cur) plus rem · (cur - full), and stop.
- Take every sum modulo 10^9 + 7 and return the total.
class Solution {
public int maxProfit(int[] inventory, int orders) {
final long MOD = 1_000_000_007L;
int[] inv = inventory.clone();
Arrays.sort(inv);
long total = 0, left = orders;
long width = 0;
for (int i = inv.length - 1; i >= 0 && left > 0; i--) {
width++;
long cur = inv[i];
long next = i > 0 ? inv[i - 1] : 0;
if (cur == next) continue;
long rows = cur - next;
if (width * rows <= left) {
total = (total + width * rangeSum(next, cur)) % MOD;
left -= width * rows;
} else {
long full = left / width, rem = left % width;
total = (total + width * rangeSum(cur - full, cur)) % MOD;
total = (total + rem * (cur - full)) % MOD;
left = 0;
}
}
return (int) total;
}
// lo + 1 + lo + 2 + ... + hi, modulo 10^9 + 7
private long rangeSum(long lo, long hi) {
return (lo + hi + 1) * (hi - lo) / 2 % 1_000_000_007L;
}
}class Solution:
def maxProfit(self, inventory: List[int], orders: int) -> int:
MOD = 10**9 + 7
inv = sorted(inventory)
total = 0
left = orders
width = 0
for i in range(len(inv) - 1, -1, -1):
if left == 0:
break
width += 1
cur = inv[i]
nxt = inv[i - 1] if i > 0 else 0
if cur == nxt:
continue
rows = cur - nxt
if width * rows <= left:
total = (total + width * self.rangeSum(nxt, cur)) % MOD
left -= width * rows
else:
full, rem = divmod(left, width)
total = (total + width * self.rangeSum(cur - full, cur)) % MOD
total = (total + rem * (cur - full)) % MOD
left = 0
return total
# lo + 1 + lo + 2 + ... + hi, modulo 10^9 + 7
def rangeSum(self, lo: int, hi: int) -> int:
return (lo + hi + 1) * (hi - lo) // 2 % (10**9 + 7)class Solution {
public:
int maxProfit(vector<int>& inventory, int orders) {
const long long MOD = 1000000007LL;
vector<int> inv = inventory;
sort(inv.begin(), inv.end());
long long total = 0, left = orders;
long long width = 0;
for (int i = (int)inv.size() - 1; i >= 0 && left > 0; i--) {
width++;
long long cur = inv[i];
long long next = i > 0 ? inv[i - 1] : 0;
if (cur == next) continue;
long long rows = cur - next;
if (width * rows <= left) {
total = (total + width * rangeSum(next, cur)) % MOD;
left -= width * rows;
} else {
long long full = left / width, rem = left % width;
total = (total + width * rangeSum(cur - full, cur)) % MOD;
total = (total + rem * (cur - full)) % MOD;
left = 0;
}
}
return (int)total;
}
private:
// lo + 1 + lo + 2 + ... + hi, modulo 10^9 + 7
long long rangeSum(long long lo, long long hi) {
return (lo + hi + 1) * (hi - lo) / 2 % 1000000007LL;
}
};function maxProfit(inventory, orders) {
const MOD = 1000000007n;
const inv = [...inventory].sort((a, b) => a - b);
let total = 0n, left = orders;
let width = 0;
for (let i = inv.length - 1; i >= 0 && left > 0; i--) {
width++;
const cur = inv[i];
const next = i > 0 ? inv[i - 1] : 0;
if (cur === next) continue;
const rows = cur - next;
if (width * rows <= left) {
total = (total + BigInt(width) * rangeSum(next, cur)) % MOD;
left -= width * rows;
} else {
const full = Math.floor(left / width), rem = left % width;
total = (total + BigInt(width) * rangeSum(cur - full, cur)) % MOD;
total = (total + BigInt(rem) * BigInt(cur - full)) % MOD;
left = 0;
}
}
return Number(total);
// lo + 1 + lo + 2 + ... + hi, modulo 10^9 + 7
function rangeSum(lo, hi) {
return (BigInt(lo + hi + 1) * BigInt(hi - lo) / 2n) % MOD;
}
}3Optimal (binary search on the threshold)
O(n log M)About log M rounds of binary search, M being the largest count (about 30 rounds), each a pass over the n colours, plus one final pass.O(1)Only a few counters; inventory is not copied or changed.The greedy sales always end the same way: there is a height t such that every ball worth more than t is sold, and a few balls worth exactly t are sold too. Let above(t) be the number of balls worth more than t, the sum of max(0, inventory[i] - t). It only shrinks as t grows, so binary search the smallest t in [0, max] with above(t) <= orders. Then sell every ball above t, adding the run t + 1 + ... + inventory[i] for each colour, and sell the remaining orders - above(t) balls at price t. Because t is the smallest such height, there are always enough colours still holding a ball worth t.
- lo = 0, hi = the largest count.
- While lo < hi: mid = lo + (hi - lo) / 2. If above(mid) <= orders, set hi = mid, else lo = mid + 1.
- t = lo. For each colour with x > t, add t + 1 + ... + x to the total and x - t to sold.
- Add (orders - sold) · t, everything modulo 10^9 + 7, and return it.
class Solution {
private static final long MOD = 1_000_000_007L;
public int maxProfit(int[] inventory, int orders) {
int lo = 0, hi = 0;
for (int x : inventory) hi = Math.max(hi, x);
// smallest threshold t whose balls above it fit in orders
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (above(inventory, mid) <= orders) hi = mid;
else lo = mid + 1;
}
int t = lo;
long total = 0, sold = 0;
for (int x : inventory) {
if (x > t) {
total = (total + rangeSum(t, x)) % MOD;
sold += x - t;
}
}
total = (total + (orders - sold) * t) % MOD;
return (int) total;
}
// how many balls are worth more than t
private long above(int[] inventory, int t) {
long count = 0;
for (int x : inventory) {
if (x > t) count += x - t;
}
return count;
}
// t + 1 + t + 2 + ... + x, modulo 10^9 + 7
private long rangeSum(long t, long x) {
return (t + x + 1) * (x - t) / 2 % MOD;
}
}class Solution:
MOD = 10**9 + 7
def maxProfit(self, inventory: List[int], orders: int) -> int:
lo, hi = 0, max(inventory)
# smallest threshold t whose balls above it fit in orders
while lo < hi:
mid = (lo + hi) // 2
if self.above(inventory, mid) <= orders:
hi = mid
else:
lo = mid + 1
t = lo
total = 0
sold = 0
for x in inventory:
if x > t:
total = (total + self.rangeSum(t, x)) % self.MOD
sold += x - t
total = (total + (orders - sold) * t) % self.MOD
return total
# how many balls are worth more than t
def above(self, inventory: List[int], t: int) -> int:
count = 0
for x in inventory:
if x > t:
count += x - t
return count
# t + 1 + t + 2 + ... + x, modulo 10^9 + 7
def rangeSum(self, t: int, x: int) -> int:
return (t + x + 1) * (x - t) // 2 % self.MODclass Solution {
static const long long MOD = 1000000007LL;
public:
int maxProfit(vector<int>& inventory, int orders) {
int lo = 0, hi = 0;
for (int x : inventory) hi = max(hi, x);
// smallest threshold t whose balls above it fit in orders
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (above(inventory, mid) <= orders) hi = mid;
else lo = mid + 1;
}
int t = lo;
long long total = 0, sold = 0;
for (int x : inventory) {
if (x > t) {
total = (total + rangeSum(t, x)) % MOD;
sold += x - t;
}
}
total = (total + (orders - sold) * t) % MOD;
return (int)total;
}
private:
// how many balls are worth more than t
long long above(vector<int>& inventory, int t) {
long long count = 0;
for (int x : inventory) {
if (x > t) count += x - t;
}
return count;
}
// t + 1 + t + 2 + ... + x, modulo 10^9 + 7
long long rangeSum(long long t, long long x) {
return (t + x + 1) * (x - t) / 2 % MOD;
}
};function maxProfit(inventory, orders) {
const MOD = 1000000007n;
let lo = 0, hi = 0;
for (const x of inventory) hi = Math.max(hi, x);
// smallest threshold t whose balls above it fit in orders
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (above(inventory, mid) <= orders) hi = mid;
else lo = mid + 1;
}
const t = lo;
let total = 0n, sold = 0;
for (const x of inventory) {
if (x > t) {
total = (total + rangeSum(t, x)) % MOD;
sold += x - t;
}
}
total = (total + BigInt(orders - sold) * BigInt(t)) % MOD;
return Number(total);
// how many balls are worth more than t
function above(inventory, t) {
let count = 0;
for (const x of inventory) {
if (x > t) count += x - t;
}
return count;
}
// t + 1 + t + 2 + ... + x, modulo 10^9 + 7
function rangeSum(t, x) {
return (BigInt(t + x + 1) * BigInt(x - t) / 2n) % MOD;
}
}Edge cases to test
- One colour only: the answer is the sum of a run of consecutive values
- orders equals the total number of balls, so every ball is sold
- Every colour holds the same number of balls
- orders and the counts near 10^9: the true total is about 5 · 10^17, so intermediate sums need 64 bits before taking the modulo
- The last level is only partly sold: some colours sell one more ball at the threshold value than others
Hints
Hint 1
Each sale should take a ball from the colour that currently has the most balls. Selling a cheaper ball first can never help.
Hint 2
A max-heap can do one sale at a time, but orders can be a billion. Group the sales instead.
Hint 3
Picture the counts as bars. The greedy sales shave the tallest bars down, level by level. Everything above some height t is sold completely.
Hint 4
The number of balls above a height t only shrinks as t grows. Binary search the smallest t with at most orders balls above it. Sell all of those, then sell the remaining orders at price t.
FAQ
What is the best time complexity for Sell Diminishing-Valued Colored Balls?
Optimal (binary search on the threshold) runs in O(n log M) time and O(1) extra space. About log M rounds of binary search, M being the largest count (about 30 rounds), each a pass over the n colours, plus one final pass.
Which pattern does Sell Diminishing-Valued Colored Balls use?
It is a binary search problem that uses the binary search on answer space pattern. Other problems with the same pattern: Koko Eating Bananas, Minimum Number of Days to Make m Bouquets, Separate Squares I.
Is there a brute force solution for Sell Diminishing-Valued Colored Balls?
Yes. Max-heap, one ball at a time takes O(n + orders · log n) time and O(n) space. The greedy rule is simple: every sale should take a ball of the colour that currently has the most balls, because that sale is worth the most and taking it now never lowers what the other sales can earn.
Which edge cases should I test for Sell Diminishing-Valued Colored Balls?
One colour only: the answer is the sum of a run of consecutive values; orders equals the total number of balls, so every ball is sold; Every colour holds the same number of balls; orders and the counts near 10^9: the true total is about 5 · 10^17, so intermediate sums need 64 bits before taking the modulo; The last level is only partly sold: some colours sell one more ball at the threshold value than others.