Skip to content

Commit 967f3ed

Browse files
authored
Create find-the-smallest-divisor-given-a-threshold.cpp
1 parent e61d254 commit 967f3ed

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int smallestDivisor(vector<int>& nums, int threshold) {
7+
int left = 1, right = *max_element(nums.cbegin(), nums.cend());
8+
while (left <= right) {
9+
const auto& mid = left + (right - left) / 2;
10+
if (check(nums, mid, threshold)) {
11+
right = mid - 1;
12+
} else {
13+
left = mid + 1;
14+
}
15+
}
16+
return left;
17+
}
18+
19+
private:
20+
bool check(const vector<int>& nums, int x, int threshold) {
21+
return accumulate(nums.cbegin(), nums.cend(), 0,
22+
[&x](const auto& a, const auto& b) {
23+
return a + (b - 1) / x + 1;
24+
})
25+
<= threshold;
26+
}
27+
};

0 commit comments

Comments
 (0)