86. Slowest eating speed
There are piles of snacks on the table, and the guests arrive in hours hours. You eat at a steady speed of speed
snacks per hour, like this: each hour you pick one pile and eat up to speed snacks from it. If the pile has fewer
than that, you finish it and wait for the next hour before starting another pile.
So at a speed of 4, a pile of 10 takes 3 hours (4, 4, then the last 2), and a pile of 3 takes 1 hour.
Write a function slowest_speed(piles, hours) that takes the list of pile sizes and the number of hours, and returns
the slowest whole-number speed that finishes every pile within hours hours.
- There are always at least as many hours as piles, so a fast enough speed always exists.
- Piles can hold up to 10^9 snacks, so trying speeds 1, 2, 3, ... one at a time is far too slow.
Example 1
piles = [5, 9, 2], hours = 63Example 2
piles = [10], hours = 34Example 3
piles = [4, 4, 4], hours = 34Constraints
pileshas 1 to 100 whole numbers, each from 1 to 10^9.hoursis a whole number fromlen(piles)to 10^9.
Submit also runs 9 more tests you can't see.
- Write a helper that works out the hours a speed needs: each pile takes its size divided by the speed, rounded up.
(pile + speed - 1) // speedrounds up without floats. - If a speed is fast enough, every faster speed is too. So binary search over the speeds from 1 to
max(piles)(eating faster than the biggest pile never helps). - When the middle speed is fast enough, it might be the answer: keep it with
high = mid. Otherwiselow = mid + 1. Stop whenlow == high.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def slowest_speed(piles, hours):
"""Find the slowest speed that eats every pile in time.
piles: list of int, the size of each pile
hours: int, the hours available, at least len(piles)
Returns: int, the smallest speed (snacks per hour)
that finishes within hours
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.