forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-time-to-eat-all-grains.cpp
39 lines (37 loc) · 1.29 KB
/
minimum-time-to-eat-all-grains.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Time: O(mlogm + nlogn + (m + n) * logr), r = 2*(max(max(hens), max(grains))-min(min(hens), min(grains))
// Space: O(1)
// binary search, greedy
class Solution {
public:
int minimumTime(vector<int>& hens, vector<int>& grains) {
const auto& check = [&](const int x) {
int i = 0;
for (const auto& h : hens) {
int c = x;
if (h - grains[i] > x) {
return false;
} else if (h - grains[i] > 0) {
const int d = h - grains[i];
c = max(x - 2 * d, (x - d) / 2); // # max(go left then right, go right then left)
}
for (; i < size(grains) && grains[i] <= h + c; ++i);
if (i == size(grains)) {
return true;
}
}
return false;
};
sort(begin(hens), end(hens));
sort(begin(grains), end(grains));
int left = 0, right = 2 * (max(hens.back(), grains.back()) - min(hens.front(), grains.front()));
while (left <= right) {
const int mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};