A book club reads a shelf of books in order. Each book must go to exactly one reader, every reader gets a contiguous run of the shelf and at least one book, and the books cannot be reordered. The club wants the reader with the most pages to have as few pages as possible.
Write two functions that take pages, an array where pages[i] is the page count of the i-th book, and readers, the number of readers.
minMaxPages(pages, readers) returns the smallest possible value of the largest number of pages any one reader gets. It returns -1 when there are more readers than books.
assignBooks(pages, readers) returns an array of length readers: how many books each reader takes, in shelf order, in a split that achieves minMaxPages. It returns null when there are more readers than books.
Rules:
When several splits achieve the best value, return the one where the first reader takes as many books as possible, then the second, and so on.
If pages is not an array of positive safe integers, or readers is not a positive safe integer, throw a TypeError.
The shelf can hold 200,000 books of up to 1,000,000,000 pages each, with up to 200,000 readers. Trying every possible limit one by one, or a dynamic program over every split point, will not finish in time.
minMaxPages([12, 34, 67, 90], 2); // 113: [12, 34, 67] and [90]assignBooks([12, 34, 67, 90], 2); // [3, 1]minMaxPages([10, 20, 30, 40], 2); // 60: [10, 20, 30] and [40]assignBooks([5, 5, 5, 5], 3); // [2, 1, 1], the earliest readers take the mostminMaxPages([7, 8], 3); // -1: three readers, two books
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.