-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookAllocate.cpp
More file actions
49 lines (48 loc) · 1.12 KB
/
bookAllocate.cpp
File metadata and controls
49 lines (48 loc) · 1.12 KB
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
//Allocate Books Problem.
#include<iostream>
#include<vector>
using namespace std;
bool isValid(vector<int> vect, int n , int m ,int maxAllowedPages){
int students=1;
int books=0;
for (int i=0 ; i<n ; i++){ //O(n)
if (vect[i]>maxAllowedPages){
return false;
}
if(books+vect[i]<=maxAllowedPages){
books+=vect[i];
}else{
students++;
books=vect[i];
}
}
return students>m ? false: true;
}
int binarySearch(vector<int> vect, int n, int m,int sum){ //O(logN*n)
if(m>n){
return -1;
}
int st=0;
int ed=sum;
int ans=-1;
while(st<=ed){
int mid=st+(ed-st)/2;
if (isValid(vect,n,m,mid)){
ans=mid;
ed=mid-1;
}else{
st=mid+1;
}
}
return ans;
}
int main(){
vector<int> vect={15,17,20,13};
int n=4,m=2;
int sum=0;
for (int val:vect){ //O(n)
sum+=val;
}
int answer=binarySearch(vect, n, m,sum);
cout<<"Minimum no. of pages: "<<answer;
}