-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBookAlocationUsingBinarySearch.cpp
49 lines (42 loc) · 1.15 KB
/
BookAlocationUsingBinarySearch.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 <iostream>
using namespace std;
class Solution {
public:
bool isPossible(int array, int noOfBooks, int noOfStudents, int mid) {
int studentCount = 1;
int pageSum = 0;
for (int j = 0; j < noOfBooks; j++) {
if (pageSum + array[j] <= mid) {
pageSum += array[j];
} else {
studentCount++;
if (studentCount > noOfStudents || array[j] > mid) {
return false;
}
pageSum = array[j];
}
}
return true;
}
int allocateBooks(int array, int noOfBooks, int noOfStudents) {
int start = 0, sum = 0;
for (int i = 0; i < noOfBooks; i++) {
sum += array[i];
}
int end = sum, answer = -1;
while (start < end) {
int mid = start + (end - start) / 2;
if (isPossible(array, noOfBooks, noOfStudents, mid)) {
answer = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return answer;
}
};
int main() {
Solution sol1;
return 0;
}