1283. Find the Smallest Divisor Given a Threshold
Intuition
Complexity
Space Complexity
Time Complexity
Code
// Helper function to calculate the total sum of ceil(num / divisor) for all elements
int calculateSum(int[] numbers, int divisor) {
int total = 0;
for (int number : numbers) {
// Use Math.ceil to ensure we round up the division
total += Math.ceil(1.0 * number / divisor);
}
return total;
}
public int smallestDivisor(int[] numbers, int threshold) {
int left = 1;
int right = 1;
int smallestValidDivisor = 0;
// Determine the upper bound for binary search (max number in array)
for (int number : numbers) {
right = Math.max(right, number);
}
// Edge case: all elements are the same
if (left == right) return left;
// Binary search for the smallest valid divisor
while (left <= right) {
int midDivisor = (left + right) / 2;
int currentSum = calculateSum(numbers, midDivisor);
if (currentSum <= threshold) {
// Current divisor is valid; try to minimize it
smallestValidDivisor = midDivisor;
right = midDivisor - 1;
} else {
// Too large a sum, need a bigger divisor
left = midDivisor + 1;
}
}
return smallestValidDivisor;
}
Previous1101. The Earliest Moment When Everyone Become FriendsNext2140. Solving Questions With Brainpower
Last updated