-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookAllocation.cpp
More file actions
33 lines (31 loc) · 898 Bytes
/
Copy pathBookAllocation.cpp
File metadata and controls
33 lines (31 loc) · 898 Bytes
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
class Solution {
public:
int countStudents(vector<int> &arr,int maxPages) {
int students = 1;
long long currentPages = 0;
for (int i=0;i<arr.size();i++) {
if (currentPages+arr[i]<=maxPages) {
currentPages += arr[i];
}else {
students++;
currentPages = arr[i];
}
}
return students;
}
int findPages(vector<int> &arr, int k) {
if(k>arr.size()) return -1;
int low = *max_element(arr.begin(), arr.end());
long long high = accumulate(arr.begin(), arr.end(), 0LL);
while (low<=high) {
int mid = low+(high-low)/2;
int studentsRequired = countStudents(arr, mid);
if(studentsRequired <= k) {
high = mid-1;
}else {
low = mid+1;
}
}
return low;
}
};