Minimum Time to Eat All Grains - Problem
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.
Input & Output
Example 1 — Basic Assignment
$
Input:
hens = [3,6], grains = [2,4,7,9]
›
Output:
3
💡 Note:
Hen at position 3 eats grains at [2,4] (time = |3-2| + |4-2| = 3), hen at position 6 eats grains at [7,9] (time = |6-7| + |9-7| = 3). Maximum time is 3.
Example 2 — Single Hen
$
Input:
hens = [5], grains = [1,3,7]
›
Output:
8
💡 Note:
Single hen at 5 must eat all grains [1,3,7]. To collect all grains from position 1 to 7, hen can go left first (time = |5-1| + |7-1| = 4 + 6 = 10) or right first (time = |5-7| + |7-1| = 2 + 6 = 8). The minimum time is 8.
Example 3 — No Grains
$
Input:
hens = [1,2,3], grains = []
›
Output:
0
💡 Note:
No grains to eat, so time required is 0.
Constraints
- 1 ≤ hens.length ≤ 20
- 1 ≤ grains.length ≤ 20
- -109 ≤ hens[i], grains[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code