Book Club Reading Plan

Mediumbinary searchAlso known as Capacity To Ship Packages Within D Days

Your book club must finish the novel in days days. You know each chapter's page count. You read chapters in order, never stop mid-chapter, and read at least one chapter on each day you use.

You want a single daily page limit that is as low as possible while still letting the club finish by the deadline.

Your task

Write dailyPageLimit(chapters, days). Split chapters, in order, into at most days consecutive groups (each day reads one group). Return the smallest possible value of the largest group's page total.

Finishing early is fine, so using fewer than days days is allowed.

dailyPageLimit(chapters: int[], days: int) → int

Examples

Example 1
Input
chapters = [12, 30, 8, 25, 15, 10]
days = 3
Output
42
Why

Read 12 + 30 = 42, then 8 + 25 = 33, then 15 + 10 = 25: the busiest day is 42. A limit of 41 needs 4 days: 12 | 30 + 8 | 25 + 15 | 10. The average, 100 / 3 ≈ 34, is not achievable.

Example 2
Input
chapters = [40, 10, 10, 10]
days = 2
Output
40
Why

The 40-page chapter cannot be split, so the limit is at least 40. A limit of 40 works, because day 1 reads that chapter and day 2 reads the other 30 pages.

Constraints

  • 1 ≤ chapters.length ≤ 10,000
  • 1 ≤ chapters[i] ≤ 10,000
  • 1 ≤ days ≤ 10,000
Start with brute force

Try every limit from the longest chapter upward with the greedy day count, stopping at the first that fits. Or try every way to cut the chapters into groups.

Trying every way to cut the chapters is exponential. Counting up through the limits costs O(n × S), and S can reach 100,000,000 pages. Binary search on the limit needs about 27 tries, and each try is one O(n) pass.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code