Skip to problem
←

Allocate Minimum Pages

Hard 0 attempts

You're given an array arr of arr.length integers, where arr[i] is the page count of the i-th book, and you need to distribute these books among m students. Books must be handed out in the order they appear — each student gets a contiguous block — and every student must receive at least one book. Choose an allocation that minimizes the largest number of pages any single student ends up with, and return that minimized maximum.

Return -1 if there are more students than books, because every student must receive at least one book.

Function contract

Implement allocateMinimumPages(arr, m), where arr contains book page counts in shelf order and m is the number of students.

Output: The smallest possible maximum pages assigned to a student, or -1 when m exceeds arr.length.

Example 1

Input
arr = [12,34,67,90]
m = 2
Output
113

Example 2

Input
arr = [10]
m = 2
Output
-1
Visual Aid
Keep each student’s books together
12346790Student 1: 113 pagesStudent 2: 90Maximum load = 113 pages

Other valid split points give maximum loads of 191 or 157 pages. This split minimizes the maximum at 113.

Constraints
  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^6
  • 1 <= m <= 10^5

Binary Search on Answer

Binary search on the maximum pages. For each candidate limit, greedily count the contiguous groups needed. A limit is feasible if at most m groups are needed: since m does not exceed the number of books, groups can be split further until every student has a non-empty group.

javascript
function allocateMinimumPages(arr, m) {
  if (m > arr.length) return -1;
  let lo = 0, hi = 0;
  for (const pages of arr) {
    lo = Math.max(lo, pages);
    hi += pages;
  }
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    let students = 1, pages = 0;
    for (const p of arr) {
      if (pages + p > mid) { students++; pages = p; }
      else pages += p;
    }
    if (students <= m) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Time: O(N log S) where S = sum of pages | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript