Approach
Sorting and greedy selection
For Minimum Time to Eat All Grains, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 26 lines of Python from the credited upstream file 2604.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def minimumTime(self, hens: list[int], grains: list[int]) -> int:3 hens.sort()4 grains.sort()5 6 def canEat(time: int) -> bool:7 """Returns True if `hens` can eat all `grains` within `time`."""8 i = 0 9 for hen in hens:10 rightMoves = time11 if grains[i] < hen:12 13 leftMoves = hen - grains[i]14 if leftMoves > time:15 return False16 leftThenRight = time - 2 * leftMoves17 rightThenLeft = (time - leftMoves) 218 rightMoves = max(0, leftThenRight, rightThenLeft)19 i = bisect.bisect_right(grains, hen + rightMoves)20 if i == len(grains):21 return True22 return False23 24 maxMoves = int(1.5 * (max(hens + grains) - min(hens + grains)))25 return bisect.bisect_left(range(maxMoves), True, key=canEat)26