#1283
Medium Algorithms Find the smallest divisor given a threshold
Array Binary Search
65.5% acceptance
Feb 25, 2026
3557
225
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
The test cases are generated so that there will be an answer.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn smallest_divisor(nums: Vec<i32>, threshold: i32) -> i32 {
let mut lo = 1i32;
let mut hi = *nums.iter().max().unwrap();
while lo < hi {
let mid = (lo + hi) / 2;
let sum: i32 = nums.iter().map(|&x| (x + mid - 1) / mid).sum();
if sum <= threshold {
hi = mid;
} else {
lo = mid + 1;
}
}
lo
}
}