⬅ Previous Topic
Minimum Days to Make M BouquetsNext Topic ⮕
Capacity to Ship Packages within D Days⬅ Previous Topic
Minimum Days to Make M BouquetsNext Topic ⮕
Capacity to Ship Packages within D DaysTopic Contents
You are given a list of positive integers nums
and a positive integer threshold
. Your task is to find the smallest positive integer divisor such that the sum of all elements in the array when each is divided by this divisor (rounded up) is less than or equal to threshold
.
ceil(num / divisor)
.threshold
.If nums
is empty or threshold
is not a valid positive number, return -1
.
low = 1
and high = max(nums)
.low ≤ high
:mid
as the potential divisor.sum(ceil(num / mid) for num in nums)
.sum ≤ threshold
: store mid
as potential answer, and search for smaller divisor by setting high = mid - 1
.low = mid + 1
.import math
def smallestDivisor(nums, threshold):
def compute_sum(divisor):
return sum(math.ceil(num / divisor) for num in nums)
low, high = 1, max(nums)
answer = high
while low <= high:
mid = (low + high) // 2
if compute_sum(mid) <= threshold:
answer = mid # Valid divisor, try smaller one
high = mid - 1
else:
low = mid + 1 # Too large sum, increase divisor
return answer
nums = [1, 2, 5, 9]
threshold = 6
print("Smallest Divisor:", smallestDivisor(nums, threshold))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In each binary search step, computing the sum involves iterating through the entire array. |
Average Case | O(n log m) | Binary search over range [1, max(nums)], and each step takes O(n) time to compute the sum. |
Worst Case | O(n log m) | Same as average case — n elements, log(max(nums)) search steps. |
O(1)
Explanation: Only a few variables are used; no extra space proportional to input size.
⬅ Previous Topic
Minimum Days to Make M BouquetsNext Topic ⮕
Capacity to Ship Packages within D DaysYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.