-
Notifications
You must be signed in to change notification settings - Fork 171
/
bookAllocation.cpp
49 lines (45 loc) · 1.14 KB
/
bookAllocation.cpp
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
#include <bits/stdc++.h>
using namespace std;
int countStudents(vector<int> &arr, int pages) {
int n = arr.size(); //size of array.
int students = 1;
long long pagesStudent = 0;
for (int i = 0; i < n; i++) {
if (pagesStudent + arr[i] <= pages) {
//add pages to current student
pagesStudent += arr[i];
}
else {
//add pages to next student
students++;
pagesStudent = arr[i];
}
}
return students;
}
int findPages(vector<int>& arr, int n, int m) {
//book allocation impossible:
if (m > n) return -1;
int low = *max_element(arr.begin(), arr.end());
int high = accumulate(arr.begin(), arr.end(), 0);
while (low <= high) {
int mid = (low + high) / 2;
int students = countStudents(arr, mid);
if (students > m) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return low;
}
int main()
{
vector<int> arr = {25, 46, 28, 49, 24};
int n = 5;
int m = 4;
int ans = findPages(arr, n, m);
cout << "The answer is: " << ans << "\n";
return 0;
}