Topics
We are given machines and a target number of products . Each machine takes seconds to produce one product. We need to find the minimum time to produce at least products using all machines working simultaneously.
Idea
The problem exhibits a crucial monotonic property. If it is possible to produce products in time , then it is also possible to produce products in any time . This monotonicity allows us to efficiently search for the minimum time using binary search on answer space (time).
The lower bound can be 0. For the upper bound, consider the fastest machine (minimum ). In the worst case, we can use only this fastest machine to produce all products, i.e . At each step of our binary search, if check(mid)
is true
, it means we can produce t
(atleast) products in time mid
. So, the minimum time might be mid
or something smaller (search in left half). If check(mid)
is false
, it means we cannot produce t
products in time mid
. So, we need more time (search in right half).
The check
func: total number of products produced by all machines in time is the sum of products from each machine:
The check(x)
function returns true
if , and false
otherwise.
Time Complexity:
Code
bool check(ll x, ll t, vector<int> &arr) {
// check if possible to make atleast `t` products in time `x`
ll products = 0;
for (int &val : arr) {
products += (x / val);
}
return products >= t;
}
void solve() {
int n, t;
cin >> n >> t;
vector<int> arr(n);
int best = INT_MAX;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
best = min(best, arr[i]);
}
ll lo = 0;
ll hi = 1LL * t * best;
ll ans = hi;
while (lo <= hi) {
ll mid = lo + (hi - lo) / 2;
if (check(mid, t, arr)) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
cout << ans << endl;
}