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 pagesipages[i]students
Example 1
Output: 113
Explanation: [12, 34, 67] and [90] give 113 and 90 pages.
Example 2
Output: 60
Explanation: [10, 20, 30] and [40] give 60 and 40 pages.
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.
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
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 lohimid
If midmidhimidmidlomid + 1lohi
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 intintlong
Java Solution
The method allocate
- First, if
is greater thanstudents , return -1, because some student would get no book.pages.length - Set the search range with one loop over the books:
becomes the biggest book, usinglo , andMath.max becomes the sum of all pages. Both arehi .long - While
is less thanlo , take the middle limithi and ask the helper methodmid how many students it takes. If that is at moststudentsNeeded , setstudents tohi ; otherwise setmid tolo .mid + 1 - Inside
,studentsNeeded starts at 1 andcount , the current student's pages, at 0. A loop goes over the books in order. Whenload plus the next book would pass the limit,load goes up andcount starts again from 0. Then the book is added toload .load - When the search loop ends,
equalslo , the first limit that works. Returnhi .lo
The main
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:
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 inthiloadlong
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]studentsNeeded
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
walks all n books once.studentsNeeded - Space: O(1). Besides the input array, the method keeps only
,lo ,hi , andmid andcount insideload , however many books there are.studentsNeeded
Shipping packages in order within a number of days is the same problem with days in place of students: see