Smallest Divisor Given a Threshold

Find the smallest divisor that keeps the sum of rounded-up quotients within a limit.

Given an array of positive integers nums and an integer threshold, choose a positive integer divisor. Divide every number in nums by it, rounding each result up, and add the results. Return the smallest divisor for which this sum is at most threshold. The threshold is never smaller than the length of nums, so an answer always exists.

Example 1
Input: nums = [1, 2, 5, 9], threshold = 6
Output: 5
Explanation: dividing by 5 gives 1 + 1 + 1 + 2 = 5, which is at most 6. Dividing by 4 gives 1 + 1 + 2 + 3 = 7, which is too much.
Example 2
Input: nums = [44, 22, 33, 11, 1], threshold = 5
Output: 44
Solution

The Idea

Picture four piles of items, with 1, 2, 5 and 9 items in them. You pack each pile into boxes of the same size, and a pile never shares a box with another pile. With boxes of 4, the pile of 9 needs three boxes: two full ones and a third that holds the last item. That is 9 divided by 4, rounded up.

So the divisor is the box size, and the sum in the problem is the number of boxes all the piles need. The threshold, 6 in Example 1, is the number of boxes you have. The question becomes: what is the smallest box size that packs everything into 6 boxes?

Try a few sizes. Boxes of 4 need 1 + 1 + 2 + 3 = 7 boxes, one too many. Boxes of 5 need 1 + 1 + 1 + 2 = 5, which fits. Boxes of 3 need 7 again. We could keep trying sizes one by one, but is there a pattern that lets us skip most of them?

There is. A bigger box never needs more boxes for the same pile. So as the divisor grows, the sum only stays the same or goes down. Look at the picture below.

For nums 1, 2, 5, 9 the sums for divisors 1 to 9 are 17, 10, 7, 7, 5, 5, 5, 5, 4. Divisors 1 to 4 give more than 6 and divisors 5 to 9 fit. The tries are 5, then 3, then 4, and the answer is 5.

The row labelled divisor holds every box size from 1 to 9, and the row labelled sum holds the boxes each one needs. The row labelled within 6? reads no, no, no, no, and then yes all the way to the end. There is only one switch from no to yes, at the dashed line, and the answer is the first yes: 5.

Because the answers switch only once, one try tells us which side of the line we are on. The first try in the picture is the middle divisor, 5, and it fits, so every divisor above 5 can be dropped. The second try, 3, does not fit, so 1 to 3 can be dropped too. The third try, 4, does not fit either, and only 5 is left.

Each try halves the divisors still in play. Searching a sorted range by testing its middle and keeping one half is called binary search, and here the range is the possible divisors, not positions in an array.

Solution Approach

Turning that idea into code means settling three things: how to compute the sum for one divisor, which divisors to search, and how to halve the range. First, though, why not just try every divisor?

Trying every divisor

What if we try 1, 2, 3 and so on until one fits? That works, but it can take as many tries as the largest number. With a largest number of one million and an answer near it, that is close to a million sums, each over the whole array. Halving the range needs only about 20 tries for a million divisors, because 220 is just over a million.

Dividing and rounding up

How do we round up, when Java's / on two positive int values drops the remainder? 9 / 4 gives 2, not 3. Adding one less than the divisor first fixes it: (9 + 3) / 4 is 12 / 4, which is 3. Any remainder at all now pushes the result up by one. When there is no remainder, as in (8 + 3) / 4, the result stays 2.

The result of a division is called the quotient, so the helper that adds the rounded-up quotients is named sumOfQuotients. Its total is kept in a long. With divisor 1 the sum is the total of all the numbers, and a long array of large numbers can add up to more than an int can store.

Which divisors to search

Where does the range start and end? The smallest divisor allowed is 1. The largest one worth trying is the largest number in nums, 9 in Example 1. Dividing by it makes every quotient 1, so the sum is the length of the array, the smallest sum any divisor can give. The problem promises that the threshold is at least that, so the top of the range always fits.

Why not start at 0? Divisor 0 is not allowed, yet a search that starts at 0 can reach it. With [1, 2, 5, 9] and a threshold of 100, every try fits, so the range keeps moving down. A version that starts at 0 tries 4, 2 and 1, then 0, and throws ArithmeticException: / by zero.

Halving the range

How does one try shrink the range? Keep two ends, lo and hi, and test the divisor in the middle, mid. If mid fits, the answer is mid or something smaller, so hi moves to mid. It does not move below mid, because mid may be the answer. If mid does not fit, neither does anything smaller, so lo moves to mid + 1.

In Example 1, lo is 1 and hi is 9. The middle, 5, fits, so hi becomes 5. The middle of 1 to 5 is 3, with a sum of 7, so lo becomes 4. Then 4 gives 7 too, lo becomes 5, and the two ends meet at the answer.

The middle is computed as lo + (hi - lo) / 2, which rounds down. Rounding down matters: when lo and hi are next to each other, mid is lo, and either branch then makes the range smaller, so the loop always ends.

Java Solution

The method smallestDivisor works in these steps:

  1. First, set lo to 1, and find hi, the largest number in nums, with one pass over the array.
  2. A while loop runs as long as lo is less than hi. Each time round, it takes mid, the middle of the range, and passes it to sumOfQuotients.
  3. Inside sumOfQuotients, a for loop divides each number by divisor, rounding up with (x + divisor - 1) / divisor, and adds the result to sum, a long.
  4. Back in the while loop, if that sum is at most threshold, set hi to mid. Otherwise set lo to mid + 1.
  5. When lo and hi meet, return lo, the smallest divisor that fits.

The main method runs both examples, Example 1's array with a threshold equal to its length and with a threshold of 100, and a single number, 7, with a threshold of 3.

Java
public class SmallestDivisor {

    public static int smallestDivisor(int[] nums, int threshold) {
        int lo = 1;
        int hi = 0;
        for (int x : nums) {
            hi = Math.max(hi, x);          // dividing by the maximum makes every term 1
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (sumOfQuotients(nums, mid) <= threshold) {
                hi = mid;                  // mid fits: the answer is mid or smaller
            } else {
                lo = mid + 1;              // mid is too small: the answer is bigger
            }
        }
        return lo;
    }

    private static long sumOfQuotients(int[] nums, int divisor) {
        long sum = 0;
        for (int x : nums) {
            sum += (x + divisor - 1) / divisor;   // x / divisor, rounded up
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(smallestDivisor(new int[] {1, 2, 5, 9}, 6));
        System.out.println(smallestDivisor(new int[] {44, 22, 33, 11, 1}, 5));
        System.out.println(smallestDivisor(new int[] {1, 2, 5, 9}, 4));
        System.out.println(smallestDivisor(new int[] {1, 2, 5, 9}, 100));
        System.out.println(smallestDivisor(new int[] {7}, 3));
    }
}

Running it prints:

Output
5
44
9
1
3

The 5 and the 44 match the examples. In Example 2 the threshold, 5, equals the number of values, so every quotient must be 1. Divisor 43 already fails: 44 / 43 rounds up to 2, and the sum is 6.

Look at the third line, 9. With a threshold of 4 for [1, 2, 5, 9], the four piles get one box each, so the box must hold all 9 items: the answer is the top of the range. The fourth line goes the other way. Divisor 1 gives a sum of 17, well within 100, so the answer is the bottom of the range, 1.

The last line, 3, comes from the single number 7. Dividing 7 by 3 and rounding up gives 3, which is within the threshold of 3, while divisor 2 gives 4.

Complexity

The work is one pass to find the largest number, plus one full sum for every try of the binary search.

  • Time: O(n log M), where n is the number of values and M is the largest one. The range of divisors, 1 to M, halves with each try, so there are about log2 M tries, and each try divides all n numbers in sumOfQuotients.
  • Space: O(1). Each quotient is added straight into one long sum and never stored, and the search keeps only lo, hi and mid.

The structure is the same as Koko Eating Bananas, where the divisor is Koko's eating speed and the threshold is the number of hours.