Allocate Books (Book Allocation Problem)

Share a row of books among students, in order, so that the busiest student reads as few pages as possible.

Given an array pages, where book i has pages[i] pages, and a number of students, give every book to one of the students. Each student gets at least one book, and each student's books must sit next to each other in the array: a student may take books 2, 3 and 4, but not books 2 and 4 alone. Among all such splits, find the one where the student with the most pages reads as few as possible, and return that number of pages. Return -1 if there are fewer books than students.

Example 1
Input: pages = [12, 34, 67, 90], students = 2
Output: 113
Explanation: [12, 34, 67] and [90] give 113 and 90 pages.
Example 2
Input: pages = [10, 20, 30, 40], students = 2
Output: 60
Explanation: [10, 20, 30] and [40] give 60 and 40 pages.
Solution

The Idea

Picture the four books of Example 1 standing on a shelf in a fixed order, with 12, 34, 67 and 90 pages. Two students share them. The first student takes some books from the left end, the second takes the rest, and nobody may skip a book. We want the busier student, the one with more pages, to read as little as possible.

With two students there is one place to cut the shelf, and three choices. Cutting after 12 gives 12 and 191 pages, so the busier student reads 191. Cutting after 34 gives 46 and 157. Cutting after 67 gives 113 and 90, so the busier student reads 113. That is the smallest of the three, so the answer is 113.

With more students there are more cuts to place, and the number of ways to place them grows fast. A shelf of 100 books shared by 10 students can be cut in about 1.7 trillion ways. Can we find the answer without trying every split?

It helps to turn the question around. Instead of asking for the best split, pick a number of pages, a limit, and ask: can the books be shared so that nobody reads more than the limit? That question is easy to answer. Hand books to the first student in order until the next book would take them past the limit, then start the next student, and count how many students that takes. Look at the picture below.

Books 12, 34, 67 and 90 handed out in order. With a limit of 112 they need 3 students: 12 and 34, then 67, then 90. With a limit of 113 they need 2: 12, 34 and 67, then 90. Every limit from 90 to 112 is too low and every limit from 113 to 203 works.

In the row labelled limit 112, student 1 takes 12 and 34, which make 46. Adding 67 would make 113, past the limit, so 67 goes to student 2. Then 67 plus 90 is also past 112, so 90 needs a student 3. Three students is one too many. In the row labelled limit 113, student 1 can take 12, 34 and 67, exactly 113 pages, and student 2 takes 90. Two students are enough, so the limit works.

The line at the bottom shows every limit from 90, the biggest book, to 203, all the pages together. Every limit up to 112 is too low, and every limit from 113 on works. Raising the limit never needs more students, so once a limit works, every higher one works too. The answer to the problem is the first limit that works.

Finding the first "works" on a line that reads "too low, too low, ..., works, works" is a job for binary search: try the middle, then throw away the half that cannot hold the answer. Searching the possible answers this way, instead of searching an array, is often called binary search on the answer.

Solution Approach

Turning that idea into code means settling five things: which limits to search, how to check one limit, how to search the limits, what to do with more students than books, and how big the page totals can get.

The range of limits

Which limits are worth trying? A limit below the biggest book can never work, because that book has to go to one student whole. A limit equal to the total of all pages always works, since one student could read everything. So the search runs from the biggest book to the total: 90 to 203 in Example 1.

Checking one limit

Why does handing out books greedily, filling each student as far as the limit allows, give the fewest students? Giving the current student one more book, when it fits, never hurts. The next student then starts further along the shelf, with fewer books left to cover. If the count is at most students, the limit works.

Needing fewer students than we have also counts as working. When there are at least as many books as students, a student with two or more books can pass their last book to a student who has none yet. That raises nobody's total, and repeating it gives every student a book.

Searching the limits

The simple way is to try every limit from the biggest book upward and stop at the first that works. In Example 1 that could mean 114 checks, and with page totals in the billions, billions of checks. Binary search keeps a range, from lo to hi, that still holds the answer, and tries the middle limit, mid.

If mid works, the answer is mid or lower, so hi becomes mid. If it does not, the answer is above mid, so lo becomes mid + 1. When lo meets hi, that limit is the answer. In Example 1 the limits tried are 146, 118, 104, 111, 115, 113 and 112: seven checks instead of up to 114.

More students than books

What if there are three students and only two books? Somebody would get no book, so no split exists. The method checks this first and returns -1 before any search starts.

Page totals beyond int

Can the totals outgrow a Java int? Its largest value is 2,147,483,647, about 2.1 billion. Two books of 2,000,000,000 pages add up to 4,000,000,000, which does not fit. A page total kept in an int would wrap around past that largest value and turn negative, which is called overflow. So the total, the limits and the running page count are long, and so is the result, because with one student the answer is the total.

Java Solution

The method allocate works in these steps:

  1. First, if students is greater than pages.length, return -1, because some student would get no book.
  2. Set the search range with one loop over the books: lo becomes the biggest book, using Math.max, and hi becomes the sum of all pages. Both are long.
  3. While lo is less than hi, take the middle limit mid and ask the helper method studentsNeeded how many students it takes. If that is at most students, set hi to mid; otherwise set lo to mid + 1.
  4. Inside studentsNeeded, count starts at 1 and load, the current student's pages, at 0. A loop goes over the books in order. When load plus the next book would pass the limit, count goes up and load starts again from 0. Then the book is added to load.
  5. When the search loop ends, lo equals hi, the first limit that works. Return lo.

The main method runs both examples, two books for three students, one student per book, one student for all the books, and two books of 2,000,000,000 pages for one student.

Java
public class AllocateBooks {

    // The smallest possible "most pages any student reads",
    // or -1 if there are fewer books than students
    public static long allocate(int[] pages, int students) {
        if (students > pages.length) {
            return -1;                    // every student needs at least one book
        }
        long lo = 0;
        long hi = 0;
        for (int p : pages) {
            lo = Math.max(lo, p);         // someone has to read the largest book
            hi += p;                      // one student could read everything
        }
        while (lo < hi) {
            long mid = lo + (hi - lo) / 2;
            if (studentsNeeded(pages, mid) <= students) {
                hi = mid;                 // a limit of mid works; try a smaller one
            } else {
                lo = mid + 1;             // mid is too low
            }
        }
        return lo;
    }

    // Give books in order; move to the next student when the limit would be passed
    private static int studentsNeeded(int[] pages, long limit) {
        int count = 1;
        long load = 0;
        for (int p : pages) {
            if (load + p > limit) {
                count++;
                load = 0;
            }
            load += p;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(allocate(new int[] {12, 34, 67, 90}, 2));
        System.out.println(allocate(new int[] {10, 20, 30, 40}, 2));
        System.out.println(allocate(new int[] {10, 20}, 3));
        System.out.println(allocate(new int[] {12, 34, 67, 90}, 4));
        System.out.println(allocate(new int[] {12, 34, 67, 90}, 1));
        System.out.println(allocate(new int[] {2000000000, 2000000000}, 1));
    }
}

Running it prints:

Output
113
60
-1
90
203
4000000000

113 and 60 are the answers to the two examples. The -1 comes from two books for three students. With four students for four books, each student gets one book, so the answer, 90, is the biggest book, the bottom of the search range. With one student the answer is 203, the top of the range.

Look at the last line: 4000000000 is almost twice what an int can hold. Only because hi, load and the return value are long does it come out right.

Is the -1 check really needed, or would the search notice the missing books by itself? It would not. With the check removed, the call for [10, 20] and 3 students returns 20, not -1. studentsNeeded only tells whether a limit needs too many students; it never notices a student left without a book.

Complexity

The work is one pass over the books for each limit the binary search tries.

  • Time: O(n log S), where n is the number of books and S the total number of pages. Each try halves the range from the biggest book to S, so there are about log S tries, and each call to studentsNeeded walks all n books once.
  • Space: O(1). Besides the input array, the method keeps only lo, hi, mid, and count and load inside studentsNeeded, however many books there are.

Shipping packages in order within a number of days is the same problem with days in place of students: see Capacity to Ship Packages Within D Days.