Understanding the Problem
We are given an array where each element represents the number of pages in a book. Our goal is to assign these books to a given number of students such that:
- Each student gets at least one book.
- Books are assigned in contiguous blocks (no skipping allowed).
- We minimize the maximum number of pages assigned to any student.
This is a classic allocation problem where we want to fairly distribute the load. The fairness is measured by how low we can keep the highest page count that any single student gets.
Step-by-Step Solution with Example
Step 1: Understand the Inputs and Outputs
Suppose we have the books [12, 34, 67, 90]
and we want to assign them to 2
students.
Each student must receive a continuous block of books. We must split this array into two parts such that the student who reads the most pages still reads as little as possible.
Step 2: Identify the Search Range
We use binary search between:
low = max(arr)
→ No student can get less than the largest book.
high = sum(arr)
→ One student takes all books.
For our example, low = 90
, high = 203
.
Step 3: Apply Binary Search to Minimize the Maximum Pages
We try to find the minimum value of the maximum pages a student reads. At each step, we pick mid = (low + high) // 2
and check:
Can we divide books into ≤ k students so that no one gets more than mid
pages?
If yes, we try to find a smaller value. If not, we search higher.
Step 4: Write a Helper Function to Check Feasibility
We count how many students are needed if each student is allowed a maximum of mid
pages. We go through the books, summing their pages until we exceed mid
, then assign to a new student.
Step 5: Apply the Logic with Our Example
Try mid = 120
. Can we divide books so no student gets more than 120 pages?
- Student 1 → 12 + 34 + 67 = 113 (OK)
- Student 2 → 90 (OK)
This is valid. Try smaller value to minimize max pages.
Step 6: Find the Minimum Possible Maximum
Keep repeating until low > high
. The lowest mid
for which allocation is possible is the answer.
In this example, the answer would be 113
— that’s the least maximum load possible.
Edge Cases
- Empty book list — Nothing to assign → return
-1
.
- Zero students — No one to assign → return
-1
.
- More students than books — Not possible to assign at least one book per student → return
-1
.
- One student — Must read all books → return
sum(arr)
.
- Equal books and students — Each gets one → return
max(arr)
.
Finally
This problem is best solved using binary search on the answer range. By narrowing down the maximum number of pages a student can take, and validating it efficiently, we avoid brute force.
Always remember to handle edge cases up front, and make sure your solution respects the constraints: contiguous blocks and at least one book per student.
This is a perfect example of optimization under constraints — a very common pattern in algorithm design!
Comments
Loading comments...