Find the Smallest Divisor Given a Threshold Problem
Description
LeetCode Problem 1283.
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
The test cases are generated so that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
Constraints:
1 <= nums.length <= 5 * 10^41 <= nums[i] <= 10^6nums.length <= threshold <= 10^6
Solution
Approach: Binary Search on the Divisor
For a divisor d, let f(d) be the sum of ceil(x / d) over all x in nums. A larger divisor never makes any quotient larger, so f never increases as d grows. That means the divisors with f(d) <= threshold form a range [answer, infinity), and we can binary search for its first value.
The search range is [1, max(nums)]: with d = max(nums), every quotient is 1, so f(d) = nums.length, which the constraints guarantee is at most threshold. Larger divisors give the same sum, so they never help.
Each step tries mid. If f(mid) <= threshold, the answer is mid or smaller, so hi = mid; otherwise it is larger, so lo = mid + 1. When lo == hi, that is the answer. The ceiling is computed without floating point as (x + d - 1) / d.
Complexity: O(n log M) time, where n is the length of nums and M its maximum: each of the O(log M) steps scans nums once. O(1) extra space.
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def fits(d: int) -> bool:
return sum((x + d - 1) // d for x in nums) <= threshold # (x + d - 1) // d is ceil(x / d)
# With d = max(nums) every quotient is 1, and len(nums) <= threshold, so the answer is in [1, max(nums)].
lo, hi = 1, max(nums)
while lo < hi:
mid = (lo + hi) // 2
if fits(mid):
hi = mid # mid works: the answer is mid or smaller
else:
lo = mid + 1
return lo