Skip to content
thesarfo

Reference

Allocate Books

Binary searching to minimize the maximum pages any one student reads, given contiguous book allocation.

views 0

arr[i] = pages in book i, m students, books assigned to students in contiguous blocks. Minimize the maximum number of pages any one student reads. (Problem link)

Search space: [max(arr), sum(arr)]. For a candidate max-pages-per-student, greedily allocate books to the current student until adding one more would exceed it, then start a new student; if you need more than m students, that candidate is infeasible.

public class BookAllocation {
static int minimizeMaxPages(int[] books, int students) {
if (students > books.length) {
return -1;
}
int low = getMax(books);
int high = getSum(books);
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isFeasible(books, students, mid)) {
result = mid;
high = mid - 1; // try a smaller maximum
} else {
low = mid + 1; // need a larger maximum
}
}
return result;
}
static boolean isFeasible(int[] books, int students, int maxPages) {
int studentCount = 1;
int currentSum = 0;
for (int pages : books) {
if (currentSum + pages > maxPages) {
studentCount++;
currentSum = pages;
if (studentCount > students) {
return false;
}
} else {
currentSum += pages;
}
}
return true;
}
static int getMax(int[] books) {
int max = 0;
for (int pages : books) max = Math.max(max, pages);
return max;
}
static int getSum(int[] books) {
int sum = 0;
for (int pages : books) sum += pages;
return sum;
}
}

Time: O(n × log(sum - max)). This is structurally the same problem as Aggressive Cows — both binary search on the answer space with a greedy feasibility check, just minimizing vs. maximizing.