Slowest Reading Pace

Medium · Binary Search · about 25 min

You must read a book before an exam. chapters[i] is the number of pages in chapter i, and you have hours hours in total. Each hour you pick one chapter and read up to k pages of it. If fewer than k pages of that chapter are left, you finish it and rest for the rest of that hour (you never start another chapter in the same hour).

Return the smallest whole number k that lets you finish every chapter within hours hours. There is always at least one chapter, and hours is at least the number of chapters.

Example: reading_pace([4, 9, 12, 5], 8) → 5 (at 5 pages an hour: 1 + 2 + 3 + 1 = 7 hours; at 4 pages: 1 + 3 + 3 + 2 = 9 hours, too many)

Constraints: 1 to 100,000 chapters; each has 1 to 1,000,000,000 pages; hours is at most 1,000,000,000.

Hints

  • If you can finish at pace k, you can also finish at any faster pace. What does that tell you about the answers?
  • Write a check: how many hours does pace k need? Each chapter needs its pages divided by k, rounded up.
  • Binary search the pace between 1 and the longest chapter, looking for the first pace whose hours fit.

Learn the pattern first: the Binary Search lesson.

More Binary Search problems