Sell Diminishing-Valued Colored Balls

Medium Binary Search Binary Search on Answer Space

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^5
  • 1 <= inventory[i] <= 10^9
  • 1 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
Max-heap, one ball at a timeO(n + orders · log n)O(n)
Sort and sell level by levelO(n log n)O(n)
Optimal (binary search on the threshold)O(n log M)O(1)

1Max-heap, one ball at a time

TimeO(n + orders · log n)Building the heap is O(n); each of the orders sales is one pop and one push.
SpaceO(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.

  1. Push every inventory count into a max-heap.
  2. 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.
  3. 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;
    }
}

2Sort and sell level by level

TimeO(n log n)Sorting dominates; the walk down the sorted counts is a single pass with O(1) work per colour.
SpaceO(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.

  1. Sort a copy of inventory. Walk i from the largest index down, adding one to width each time.
  2. cur = inv[i], next = inv[i - 1] (or 0 for the last one). If they are equal, keep going so width grows.
  3. If width · (cur - next) <= left, add width · (next + 1 + ... + cur) and subtract those sales from left.
  4. Otherwise full = left / width, rem = left % width: add width · (cur - full + 1 + ... + cur) plus rem · (cur - full), and stop.
  5. 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;
    }
}

3Optimal (binary search on the threshold)

TimeO(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.
SpaceO(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.

  1. lo = 0, hi = the largest count.
  2. While lo < hi: mid = lo + (hi - lo) / 2. If above(mid) <= orders, set hi = mid, else lo = mid + 1.
  3. t = lo. For each colour with x > t, add t + 1 + ... + x to the total and x - t to sold.
  4. 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;
    }
}

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.