Given an array arr[], where arr[i] represents the number of pages in the i-th book, and an integer k denoting the total number of students, allocate all books to the students such that:
- Each student gets at least one book.
- Books are allocated in a contiguous sequence.
- The maximum number of pages assigned to any student is minimized.
If it is not possible to allocate all books among k students under these conditions, return -1.
Examples:
Input: arr[] = [12, 34, 67, 90], k = 2
Output: 113
Explanation: Books can be distributed in following ways:
- [12] and [34, 67, 90] - The maximum pages assigned to a student is 34 + 67 + 90 = 191.
- [12, 34] and [67, 90] - The maximum pages assigned to a student is 67 + 90 = 157.
- [12, 34, 67] and [90] - The maximum pages assigned to a student is 12 + 34 + 67 = 113.
The third combination has the minimum pages assigned to a student which is 113.
Input: arr[] = [15, 17, 20], k = 5
Output: -1
Explanation: Since there are more students than total books, it's impossible to allocate a book to each student.
Input: arr[] = [22, 23, 67], k = 1
Output: 112
Explanation: Since there is only 1 student, all books are assigned to that student. So, maximum pages assigned to a student is 22 + 23 + 67 = 112.
[Naive Approach] By Iterating Over All Possible Page Limits
The approach is to search for the minimum possible value of the maximum number of pages that can be assigned to any student.
- The lowest possible page limit is the maximum number of pages in a single book, since that book must be assigned to some student.
- The highest possible page limit is the total number of pages across all books, which would happen if one student gets all the books.
To check if a given page limit can work, we simulate the process of assigning books to students:
We start with the first student and keep assigning books one by one until adding the next book would exceed the current page limit. At that point, we assign books to the next student, and continue this process.
As soon as we find the smallest page limit that allows us to allocate all books to exactly k
students, we return it.
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
bool check(vector<int> &arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.size(); i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
int findPages(vector<int> &arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.size())
return -1;
// minimum and maximum possible page limits
int minPageLimit = *max_element(arr.begin(), arr.end());
int maxPageLimit = accumulate(arr.begin(), arr.end(), 0);
// iterating over all possible page limits
for(int i = minPageLimit; i <= maxPageLimit; i++) {
// return the first page limit with we can
// allocate books to all k students
if(check(arr, k, i))
return i;
}
return -1;
}
int main() {
vector<int> arr = {12, 34, 67, 90};
int k = 2;
cout << findPages(arr, k);
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
bool check(int arr[], int n, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < n; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
int findPages(int arr[], int n, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > n)
return -1;
// minimum and maximum possible page limits
int minPageLimit = arr[0];
int maxPageLimit = 0;
for(int i = 0; i < n; i++) {
if(arr[i] > minPageLimit) minPageLimit = arr[i];
maxPageLimit += arr[i];
}
// iterating over all possible page limits
for(int i = minPageLimit; i <= maxPageLimit; i++) {
// return the first page limit with we can
// allocate books to all k students
if(check(arr, n, k, i))
return i;
}
return -1;
}
int main() {
int arr[] = {12, 34, 67, 90};
int k = 2;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", findPages(arr, n, k));
return 0;
}
Java
import java.util.Arrays;
class GfG {
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
static boolean check(int[] arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
static int findPages(int[] arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.length)
return -1;
// minimum and maximum possible page limits
int minPageLimit = Arrays.stream(arr).max().getAsInt();
int maxPageLimit = Arrays.stream(arr).sum();
// iterating over all possible page limits
for(int i = minPageLimit; i <= maxPageLimit; i++) {
// return the first page limit with we can
// allocate books to all k students
if(check(arr, k, i))
return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {12, 34, 67, 90};
int k = 2;
System.out.println(findPages(arr, k));
}
}
Python
def check(arr, k, pageLimit):
# starting from the first student
cnt = 1
pageSum = 0
for pages in arr:
# if adding the current book exceeds the page
# limit, assign the book to the next student
if pageSum + pages > pageLimit:
cnt += 1
pageSum = pages
else:
pageSum += pages
# if books can assigned to less than k students then
# it can be assigned to exactly k students as well
return cnt <= k
def findPages(arr, k):
# if number of students are more than total books
# then allocation is not possible
if k > len(arr):
return -1
# minimum and maximum possible page limits
minPageLimit = max(arr)
maxPageLimit = sum(arr)
# iterating over all possible page limits
for i in range(minPageLimit, maxPageLimit + 1):
# return the first page limit with we can
# allocate books to all k students
if check(arr, k, i):
return i
return -1
if __name__ == "__main__":
arr = [12, 34, 67, 90]
k = 2
print(findPages(arr, k))
C#
using System;
using System.Linq;
class GfG {
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
static bool check(int[] arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.Length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
static int findPages(int[] arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.Length)
return -1;
// minimum and maximum possible page limits
int minPageLimit = arr.Max();
int maxPageLimit = arr.Sum();
// iterating over all possible page limits
for(int i = minPageLimit; i <= maxPageLimit; i++) {
// return the first page limit with we can
// allocate books to all k students
if(check(arr, k, i))
return i;
}
return -1;
}
static void Main() {
int[] arr = {12, 34, 67, 90};
int k = 2;
Console.WriteLine(findPages(arr, k));
}
}
JavaScript
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
function check(arr, k, pageLimit) {
// starting from the first student
let cnt = 1;
let pageSum = 0;
for(let i = 0; i < arr.length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
function findPages(arr, k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.length)
return -1;
// minimum and maximum possible page limits
const minPageLimit = Math.max(...arr);
const maxPageLimit = arr.reduce((a, b) => a + b, 0);
// iterating over all possible page limits
for(let i = minPageLimit; i <= maxPageLimit; i++) {
// return the first page limit with we can
// allocate books to all k students
if(check(arr, k, i))
return i;
}
return -1;
}
// Driver Code
const arr = [12, 34, 67, 90];
const k = 2;
console.log(findPages(arr, k));
Time Complexity: O(n × (sum(arr) - max(arr))), where n is the total number of books, sum(arr) is the total number of pages in all the books and max(arr) is maximum number of pages in any book.
Auxiliary Space: O(1)
[Expected Approach] Using Binary Search
The maximum number of pages (page limit) that a student can be allocated has a monotonic property:
- If at a page limit p, books cannot be allocated to all k students, then we need to reduce the page limit to ensure more students receive books.
- If at a page limit p, we can allocate books to more than k students, then we need to increase the page limit so that fewer students are allocated books.
Therefore, we can apply binary search to minimize the maximum pages a student can be allocated. To check the number of students that can be allotted books for any page limit, we start assigning books to the first student until the page limit is reached, then move to the next student.
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
bool check(vector<int> &arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.size(); i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
int findPages(vector<int> &arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.size())
return -1;
// search space for Binary Search
int lo = *max_element(arr.begin(), arr.end());
int hi = accumulate(arr.begin(), arr.end(), 0);
int res = -1;
while(lo <= hi) {
int mid = lo + (hi - lo)/2;
if(check(arr, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
int main() {
vector<int> arr = {12, 34, 67, 90};
int k = 2;
cout << findPages(arr, k);
return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
bool check(int arr[], int n, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < n; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
int findPages(int arr[], int n, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > n)
return -1;
// maximum element of the array is minimum page limit
int lo = arr[0];
for(int i = 1; i < n; i++)
if(arr[i] > lo) lo = arr[i];
// summation of all element is maximum page limit
int hi = 0;
for(int i = 0; i < n; i++)
hi += arr[i];
int res = -1;
while(lo <= hi) {
int mid = lo + (hi - lo)/2;
if(check(arr, n, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
int main() {
int arr[] = {12, 34, 67, 90};
int k = 2;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", findPages(arr, n, k));
return 0;
}
Java
import java.util.Arrays;
class GfG {
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
static boolean check(int[] arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
static int findPages(int[] arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.length)
return -1;
// search space for Binary Search
int lo = Arrays.stream(arr).max().getAsInt();
int hi = Arrays.stream(arr).sum();
int res = -1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(check(arr, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, 34, 67, 90};
int k = 2;
System.out.println(findPages(arr, k));
}
}
Python
# function to check if books can be allocated to
# all k students without exceeding 'pageLimit'
def check(arr, k, pageLimit):
# starting from the first student
cnt = 1
pageSum = 0
for pages in arr:
# if adding the current book exceeds the page
# limit, assign the book to the next student
if pageSum + pages > pageLimit:
cnt += 1
pageSum = pages
else:
pageSum += pages
# if books can assigned to less than k students then
# it can be assigned to exactly k students as well
return cnt <= k
def findPages(arr, k):
# if number of students are more than total books
# then allocation is not possible
if k > len(arr):
return -1
# search space for Binary Search
lo = max(arr)
hi = sum(arr)
res = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
if check(arr, k, mid):
res = mid
hi = mid - 1
else:
lo = mid + 1
return res
if __name__ == "__main__":
arr = [12, 34, 67, 90]
k = 2
print(findPages(arr, k))
C#
using System;
using System.Linq;
class GfG {
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
static bool check(int[] arr, int k, int pageLimit) {
// starting from the first student
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.Length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
static int findPages(int[] arr, int k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.Length)
return -1;
// search space for Binary Search
int lo = arr.Max();
int hi = arr.Sum();
int res = -1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(check(arr, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
static void Main() {
int[] arr = {12, 34, 67, 90};
int k = 2;
Console.WriteLine(findPages(arr, k));
}
}
JavaScript
// function to check if books can be allocated to
// all k students without exceeding 'pageLimit'
function check(arr, k, pageLimit) {
// starting from the first student
let cnt = 1;
let pageSum = 0;
for(let i = 0; i < arr.length; i++) {
// if adding the current book exceeds the page
// limit, assign the book to the next student
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
// if books can assigned to less than k students then
// it can be assigned to exactly k students as well
return (cnt <= k);
}
function findPages(arr, k) {
// if number of students are more than total books
// then allocation is not possible
if(k > arr.length)
return -1;
// search space for Binary Search
let lo = Math.max(...arr);
let hi = arr.reduce((a, b) => a + b, 0);
let res = -1;
while(lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
if(check(arr, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
// Driver Code
const arr = [12, 34, 67, 90];
const k = 2;
console.log(findPages(arr, k));
Time Complexity: O(n × log(sum(arr) - max(arr))), where n is the total number of books, sum(arr) is the total number of pages in all the books and max(arr) is maximum number of pages in any book.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem