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.
1public class Solution {
2 public int smallestDivisor(int[] nums, int threshold) {
3 int left = 1, right = 1000000;
4 while (left < right) {
5 int mid = (left + right) / 2;
6 int sum = 0;
7 for (int num : nums) {
8 sum += (num + mid - 1) / mid;
9 }
10 if (sum > threshold) {
11 left = mid + 1;
12 } else {
13 right = mid;
14 }
15 }
16 return left;
17 }
18}
This Java solution follows the same binary search strategy as the C and C++ solutions. It determines the smallest divisor where the sum of the ceilings of the divisions does not exceed 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.