Book Allocation Problem
HardMinimise the largest allocation
Problem
Given an array nums of n integers, where nums[i] represents the number of pages in the i-th book, and an integer m representing the number of students, allocate all the books to the students so that each student gets at least one book, each book is allocated to only one student, and the allocation is contiguous. Allocate the books to m students in such a way that the maximum number of pages assigned to a student is minimized. If the allocation of books is not possible, return -1.
Binary-search the page limit: check how many students it needs, shrinking until it fits.
The idea
Binary search the maximum number of pages any student may receive, and greedily hand out books in order counting how many students that limit needs. Fewer students needed than allowed means the limit can be tightened.
The trick
- Search range: max(pages) to sum(pages).
- Impossible when there are more students than books.
- This 'minimise the maximum' shape covers painter's partition and split-array too.
Step 1 of 26. Brute force: try every page-limit until the books fit 2 students. Values: 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203. candidates 114.
Try every limit.
1let best = -1;2for (let cap = maxPage; cap <= sum && best < 0; cap++)3 if (studentsNeeded(cap) <= students) best = cap;4return best;Input
- array
- [90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, …]
Memory
- try
- —
- candidates
- 114
- limit
- —
Output
- limit
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- pages = [12, 34, 67, 90], students = 2
- Output:
- 113
- Explanation:
- Split so the busiest student reads 113 pages.
Example 2
- Input:
- pages = [25, 46, 28, 49, 24], students = 4
- Output:
- 71
- Explanation:
- Fairest max load is 71.
Example 3
- Input:
- pages = [5, 17, 100, 11], students = 4
- Output:
- 100
- Explanation:
- One book of 100 forces max 100.
Constraints
- 1 <= n, m <= 10^4
- 1 <= nums[i] <= 10^5
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.