Practice › Binary Search
Smallest Divisor under a Threshold
Medium · Binary Search · Asked at Google, Amazon, Salesforce
Choose a positive integer divisor d, divide every element by it and round up, then add the results. Print the smallest d for which this sum is at most threshold.
Input
First line: n threshold. Second line: n positive integers.
Output
The smallest valid divisor.
Constraints
- 1 ≤ n ≤ 5 × 10^4
- 1 ≤ a[i] ≤ 10^6
- n ≤ threshold ≤ 10^6
The sum only goes down as d grows, so binary search d over [1, max(a)]: if the sum for d fits under the threshold, try smaller; otherwise larger. ceil(x / d) = (x + d − 1) / d.
Example 1
Input
4 6 1 2 5 9
Output
5
Example 2
Input
5 11 44 22 33 11 1
Output
11
Hints
- A bigger divisor never makes the sum bigger.
- So the valid divisors form a range [answer, ∞) — binary search for its start.
- d = max(a) always works, since every term becomes 1 and threshold ≥ n.
Approach
Binary search d in [1, max(a)]. For a candidate d compute Σ ceil(a[i] / d) = Σ (a[i] + d − 1) / d. If it is ≤ threshold, d works — search lower (hi = d); otherwise search higher (lo = d + 1). Each check is O(n), and there are about 20 checks.
Complexity: O(n log max(a)) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long t;
cin >> n >> t;
vector<long long> a(n);
for (auto &x : a) cin >> x;
long long lo = 1, hi = *max_element(a.begin(), a.end());
while (lo < hi) {
long long d = (lo + hi) / 2, sum = 0;
for (long long x : a) sum += (x + d - 1) / d;
if (sum <= t) hi = d;
else lo = d + 1;
}
cout << lo << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, t = data[0], data[1]
a = data[2 : 2 + n]
lo, hi = 1, max(a)
while lo < hi:
d = (lo + hi) // 2
if sum((x + d - 1) // d for x in a) <= t:
hi = d
else:
lo = d + 1
print(lo)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long t = (long) in.nval;
long[] a = new long[n];
long hi = 1;
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
hi = Math.max(hi, a[i]);
}
long lo = 1;
while (lo < hi) {
long d = (lo + hi) / 2, sum = 0;
for (long x : a) sum += (x + d - 1) / d;
if (sum <= t) hi = d;
else lo = d + 1;
}
System.out.println(lo);
}
}Solve Smallest Divisor under a Threshold online · All practice problems