Skip to content
Algorithms for Beginners

Problems / Binary search

Slowest speed that finishes

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

You have a stack of books, and pages[i] is the number of pages in book i. You have hours hours to read them all.

You read at a steady speed of s pages per hour. Each hour, you work on one book only: if you finish a book partway through an hour, you rest until the next hour starts. So a book of 7 pages at speed 3 takes 3 hours (3, then 3, then the last 1).

Return the slowest whole-number speed that lets you finish every book within hours.

Examples

  1. Example 1

    Input
    pages = [4, 9, 2, 13], hours = 9
    Output
    4

    At 4 pages an hour: 1 + 3 + 1 + 4 = 9 hours. At 3 it would take 2 + 3 + 1 + 5 = 11.

  2. Example 2

    Input
    pages = [25, 8, 17, 30, 12], hours = 5
    Output
    30

    5 books in 5 hours means one hour per book, so you must read the biggest (30 pages) in an hour.

  3. Example 3

    Input
    pages = [25, 8, 17, 30, 12], hours = 7
    Output
    17

    At 17 pages an hour: 2 + 1 + 1 + 2 + 1 = 7 hours.

Rules

  • pages has between 1 and 10,000 books, each with 1 to 1,000,000,000 pages.
  • hours is at least the number of books (so a fast enough speed always works) and at most 1,000,000,000.
Words on this page, in plain English (1)Open if any word is new to you
Stack
A pile where you only touch the top: add with push, take with pop. The last thing in is the first out, like a pile of plates.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function slowestSpeed(pages, hours) {
  // Return the slowest speed that finishes in time.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in binary search