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
Minimum Time to Eat All Grains INPUT Number Line (positions) 2 3 4 6 7 9 H1 H2 = Hen = Grain hens = [3, 6] 3 6 grains = [2, 4, 7, 9] 2 4 7 9 n=2 hens, m=4 grains Goal: Min time for all grains DP ALGORITHM 1 Sort Arrays Sort hens and grains by pos 2 Binary Search on Time Search range [0, max_dist] 3 DP Check Feasibility Can all grains be eaten in T? 4 Greedy Assignment Each hen eats reachable grains Binary Search Steps: T=5: OK | T=2: FAIL T=3: OK | T=2: FAIL Result: T=3 (minimum) Hen1(3)-->grains[2,4] Hen2(6)-->grains[7,9] FINAL RESULT Optimal Assignment: Hen 1 at pos 3 Eats grains at 2, 4 Time: max(1,1) = 1 sec Hen 2 at pos 6 Eats grains at 7, 9 Time: 3 sec (to pos 9) OUTPUT 3 Minimum time = 3 sec All 4 grains eaten OK - Verified Key Insight: Binary search on the answer (time T). For each T, greedily check if each hen can eat all remaining grains within its reach. A hen at pos H can reach grains in range [H-T, H+T] or [H-2T, H+T] if going left first. TutorialsPoint - Minimum Time to Eat All Grains | DP + Binary Search Approach
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen