-
Notifications
You must be signed in to change notification settings - Fork 0
/
Allocate Books
67 lines (56 loc) · 1.61 KB
/
Allocate Books
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Given an array of integers A of size N and an integer B.
The College library has N books. The ith book has A[i] number of pages.
You have to allocate books to B number of students so that the maximum number of pages allocated to a student is minimum.
A book will be allocated to exactly one student.
Each student has to be allocated at least one book.
Allotment should be in contiguous order, for example: A student cannot be allocated book 1 and book 3, skipping book 2.
Calculate and return that minimum possible number.
NOTE: Return -1 if a valid assignment is not possible.
A = [12, 34, 67, 90]
B = 2
Output:
113
bool isAllocationPossible(int barrier, vector<int>&arr, int totalStudents){
int n=arr.size();
int allocatedStudent=1;
int pages=0;
for(int i=0;i<n;i++){
if(arr[i]>barrier)return false;
if(pages + arr[i]>barrier){
allocatedStudent+=1;
// pages=0;
pages=arr[i];
}
else{
pages+=arr[i];
}
}
if(allocatedStudent > totalStudents){
return false;
}
return true;
}
int Solution::books(vector<int> &A, int B) {
int mini=INT_MAX;
int sum=0;
int n=A.size();
if(n<B)return -1;//very important to check this condition
for(int i=0;i<n;i++){
sum+=A[i];
mini=min(mini,A[i]);
}
int low=mini;
int high=sum;
int res=-1;
while(low<=high){
int mid= low + (high - low )/2;
if(isAllocationPossible(mid,A,B)){
res=mid;
high= mid-1;
}
else{
low=mid+1;
}
}
return res;
}