Q1283. Find the Smallest Divisor Given a Threshold
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed 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 to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
At the very beginning, I was thinking about a fast way to calculate the answer since it is about dividing something. The annoying thing is about how to handle these +1 or +0 situation for rounding.
With some effort, I found it non-trivial to handle. The difficulty is that I could not find a good way to keep track of whether a divisor will give +1 or +0 for a number in the list.
It turns out that the solution is a direct extension of the brute force solution. For brute force, we start from divisor = 1 and keep increasing the divisor until it gives the result smaller than the threshold.
The improvement is to use binary search. Note that we know that the solution is between 1 and max(nums). Let’s keep the left boundary not passing the threshold. And keep right boundary passing the threshold. The goal is to have the right boundary going down.
The Python submission.
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
if sum(nums) <= threshold:
return 1
return self.bin_search(nums, 1, max(nums), threshold)
def eval(self, nums, ii):
res = 0
for n in nums:
if n % ii == 0:
res += n // ii
else:
res += n // ii + 1
return res
def bin_search(self, nums, l, r, thres):
# print(thres, l, r)
if l == r or l == r - 1:
return r
mid = (l + r) // 2
val = self.eval(nums, mid)
if val > thres:
return self.bin_search(nums, mid, r, thres)
else:
return self.bin_search(nums, l, mid, thres)