Editor

Minimum Reading Speed

#143 · Sorting and searching · Advanced · 130 XP · about 25 min

You have a pile of books to finish before an exam, and pages[i] is the length of book i. You have hours hours. Each hour you pick one book and read up to speed pages of it. If the book has fewer pages left than that, you finish it and rest until the hour is over: you never start a second book in the same hour.

Write min_reading_speed(pages, hours) that returns the smallest whole-number speed that lets you finish every book within hours hours. There are always at least as many hours as books, so an answer exists.

Examples

min_reading_speed([12, 7, 30, 5], 6)   # returns 12
min_reading_speed([12, 7, 30, 5], 4)   # returns 30
min_reading_speed([100], 7)            # returns 15

At 12 pages an hour the books take 1 + 1 + 3 + 1 = 6 hours. At 11 pages an hour the first book needs 2 hours and the total becomes 7, which is too many.

Constraints

  • 1 <= len(pages) <= 10,000
  • len(pages) <= hours <= 10^9
  • 1 <= pages[i] <= 10^9

Note

Trying speeds 1, 2, 3 and so on could take a billion tries when books are long. Aim for a few dozen tries.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.