There are n hens and m grains on a line. You are given the initial positions of the hens and the grains in two integer arrays hens and grains
of size n and m respectively.
Any hen can eat a grain if they are on the same position. The time taken for this is negligible. One hen can also eat multiple grains.
In 1 second, a hen can move right or left by 1 unit. The hens can move simultaneously and independently of each other.
Return theminimum time to eat all grains if the hens act optimally.
Input: hens =[3,6,7], grains =[2,4,7,9]Output: 2Explanation:
One of the ways hens eat all grains in2 seconds is described below:- The first hen eats the grain at position 2in1 second.- The second hen eats the grain at position 4in2 seconds.- The third hen eats the grains at positions 7 and 9in2 seconds.So, the maximum time needed is2.It can be proven that the hens cannot eat all grains before 2 seconds.
Example 2:
1
2
3
4
5
6
7
8
9
Input: hens =[4,6,109,111,213,215], grains =[5,110,214]Output: 1Explanation:
One of the ways hens eat all grains in1 second is described below:- The first hen eats the grain at position 5in1 second.- The fourth hen eats the grain at position 110in1 second.- The sixth hen eats the grain at position 214in1 second.- The other hens do not move.So, the maximum time needed is1.
The minimum time is the smallest t such that all grains can be assigned to hens, with each hen able to reach all its assigned grains within t seconds. We can use binary search on t and check feasibility using a greedy two-pointer approach.
classSolution {
public:int minimumTime(vector<int>& hens, vector<int>& grains) {
sort(hens.begin(), hens.end());
sort(grains.begin(), grains.end());
int left =0, right =1e9, ans =-1;
while (left <= right) {
int mid = left + (right - left) /2;
int i =0, j =0, n = hens.size(), m = grains.size();
while (i < n && j < m) {
int start = j;
while (j < m && abs(grains[j] - hens[i]) <= mid) ++j;
if (start == j) ++i;
}
if (j == m) {
ans = mid;
right = mid -1;
} else {
left = mid +1;
}
}
return ans;
}
};
classSolution {
publicintminimumTime(int[] hens, int[] grains) {
Arrays.sort(hens);
Arrays.sort(grains);
int left = 0, right = (int)1e9, ans =-1;
while (left <= right) {
int mid = left + (right - left) / 2;
int i = 0, j = 0, n = hens.length, m = grains.length;
while (i < n && j < m) {
int start = j;
while (j < m && Math.abs(grains[j]- hens[i]) <= mid) ++j;
if (start == j) ++i;
}
if (j == m) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
}