[Geeks for Geeks] Allocate minimum number of pages

Allocate minimum number of pages

You are given N number of books. Every ith book has Ai number of pages.

You have to allocate contiguous books to M number of students. There can be many ways or permutations to do so. In each permutation, one of the M students will be allocated the maximum number of pages. Out of all these permutations, the task is to find that particular permutation in which the maximum number of pages allocated to a student is the minimum of those in all the other permutations and print this minimum value.

Each book will be allocated to exactly one student. Each student has to be allocated at least one book.

Note: Return -1 if a valid assignment is not possible, and allotment should be in contiguous order (see the explanation for better understanding).

  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
//Function to find minimum number of pages.
int findPages(int A[], int N, int M) {
int l = 0, r = INT_MAX, res = INT_MAX;
while(l <= r) {
int m = l + (r - l) / 2;
int assign = 1, sum = 0, ma = 0;
for(int i = 0; i < N; i++) {
if(sum + A[i] > m) {
sum = A[i];
assign++;
} else sum += A[i];
ma = max(sum, ma);
}
if(assign == M) res = min(res, ma);
if(assign <= M) r = m - 1;
else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/allocate-minimum-number-of-pages/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.