Minimum Time to Eat All Grains Problem
Description
LeetCode Problem 2604.
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 the minimum time to eat all grains if the hens act optimally.
Example 1:
Input: hens = [3,6,7], grains = [2,4,7,9]
Output: 2
Explanation:
One of the ways hens eat all grains in 2 seconds is described below:
- The first hen eats the grain at position 2 in 1 second.
- The second hen eats the grain at position 4 in 2 seconds.
- The third hen eats the grains at positions 7 and 9 in 2 seconds.
So, the maximum time needed is 2.
It can be proven that the hens cannot eat all grains before 2 seconds.
Example 2:
Input: hens = [4,6,109,111,213,215], grains = [5,110,214]
Output: 1
Explanation:
One of the ways hens eat all grains in 1 second is described below:
- The first hen eats the grain at position 5 in 1 second.
- The fourth hen eats the grain at position 110 in 1 second.
- The sixth hen eats the grain at position 214 in 1 second.
- The other hens do not move.
So, the maximum time needed is 1.
Constraints:
1 <= hens.length, grains.length <= 2*10^40 <= hens[i], grains[j] <= 10^9
Solution
Approach: Sorting + Binary Search
Sort the hens and the grains by position, then binary search on the time t: find the smallest t such that every grain can be eaten within t seconds.
To check a given t, process the hens from left to right with a pointer j at the leftmost grain not yet eaten. For a hen at x and that grain at y:
- If
y <= x, letd = x - y. Ifd > tthis grain can never be reached, sotfails. Otherwise movejpast all grains up tox, then keep going right while the hen can still reach the next grain, which costsmin(d, grains[j] - x) + grains[j] - y(go left first or right first, whichever is cheaper). - If
y > x, movejright whilegrains[j] - x <= t.
t works if j reaches the end of the grains.
Complexity: time O(n log n + m log m + (m + n) log U), space O(log n + log m), where n and m are the numbers of hens and grains and U is the largest position.
class Solution:
def minimumTime(self, hens: List[int], grains: List[int]) -> int:
def check(t):
j = 0
for x in hens:
if j == m:
return True
y = grains[j]
if y <= x:
d = x - y
if d > t:
return False
while j < m and grains[j] <= x:
j += 1
while j < m and min(d, grains[j] - x) + grains[j] - y <= t:
j += 1
else:
while j < m and grains[j] - x <= t:
j += 1
return j == m
hens.sort()
grains.sort()
m = len(grains)
r = abs(hens[0] - grains[0]) + grains[-1] - grains[0] + 1
l = 0
while l < r:
mid = (l + r) >> 1
if check(mid):
r = mid
else:
l = mid + 1
return l