[LeetCode] Find the Smallest Divisor Given a Threshold

1283. Find the Smallest Divisor Given a Threshold

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int search(vector<int>& A, int m) {
return accumulate(begin(A), end(A), 0.0, [&](int sum, int a) {
return sum + ceil(1.0 * a / m);
});
}
public:
int smallestDivisor(vector<int>& A, int t) {
int l = 1, r = 1e6;
while(l <= r) {
int m = (l + r) / 2;
int s = search(A, m);
if(s > t) l = m + 1;
else r = m - 1;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/28/PS/LeetCode/find-the-smallest-divisor-given-a-threshold/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.