This approach uses binary search to efficiently find the smallest divisor. The possible divisors can range from 1 to the maximum number in the array. For each candidate divisor, divide each number in the array, take the ceiling of the division result, sum it up, and compare against the threshold.
Binary search helps minimize the number of trials by adjusting the divisor range based on whether the threshold condition is met or not for a given divisor.
Time Complexity: O(n * log(max(nums))) where n is the number of elements in nums. Space Complexity: O(1) as we use constant additional space.
1#include <stdio.h>
2#include <math.h>
3
4int smallestDivisor(int* nums, int numsSize, int threshold) {
5 int left = 1, right = 1e6;
6 while (left < right) {
7 int mid = (left + right) / 2;
8 int sum = 0;
9 for (int i = 0; i < numsSize; ++i) {
10 sum += (nums[i] + mid - 1) / mid; // Equivalent to ceil(nums[i] / mid)
11 }
12 if (sum > threshold) {
13 left = mid + 1;
14 } else {
15 right = mid;
16 }
17 }
18 return left;
19}
The code uses binary search to find the smallest divisor. The loop continues until 'left' and 'right' converge. For each middle value, we compute the sum of divisions rounded up (utilizing integer arithmetic for efficiency), and adjust the search range based on whether this sum is more or less than the threshold.
This method involves a simple linear search from divisor = 1 upwards, incrementally checking each candidate as a divisor. This approach is less efficient compared to binary search but helps understand the problem in a straightforward manner. We calculate the total sum of the divisions for each divisor and stop when the sum is less or equal to the threshold. Ensuring progressively checking divisors until a valid one is found assures correctness.
Time Complexity: Potentially O(n * max(nums)). Space Complexity: O(1).
1#include <stdio.h>
2#include <math.h>
3
4int smallestDivisor(int* nums, int numsSize, int threshold) {
5 for (int divisor = 1; ; ++divisor) {
6 int sum = 0;
7 for (int i = 0; i < numsSize; ++i) {
8 sum += (nums[i] + divisor - 1) / divisor;
9 }
10 if (sum <= threshold) {
11 return divisor;
12 }
13 }
14}
This code initiates a loop to test each divisor starting from 1 upwards until it finds the smallest divisor satisfying the condition. The ceiling of division is calculated with the same integer math trick as before.