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.
1function smallestDivisor(nums, threshold) {
2 let left = 1, right = 1000000;
3 while (left < right) {
4 let mid = Math.floor((left + right) / 2);
5 let sum = nums.reduce((acc, num) => acc + Math.ceil(num / mid), 0);
6 if (sum > threshold) {
7 left = mid + 1;
8 } else {
9 right = mid;
10 }
11 }
12 return left;
13}
The JavaScript solution uses a combination of Math.ceil and Array.reduce to quickly compute the division sums across the numbers, adjusting the bounds for binary search based on whether the current divisor's result meets the threshold criteria.
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).
1public class Solution {
2 public int smallestDivisor(int[] nums, int threshold) {
3 for (int divisor = 1; ; divisor++) {
4 int sum = 0;
5 for (int num : nums) {
6 sum += (num + divisor - 1) / divisor;
7 }
8 if (sum <= threshold) {
9 return divisor;
10 }
11 }
12 }
13}
Through iterative trial and error, this Java solution computes divisor sums, extending the range upwards until a divisor satisfies the condition of having a sum smaller than or equal to the threshold.