-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgfg_AllocateMinimumPages.cpp
More file actions
executable file
·39 lines (35 loc) · 1.03 KB
/
gfg_AllocateMinimumPages.cpp
File metadata and controls
executable file
·39 lines (35 loc) · 1.03 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
// https://www.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/1
class Solution {
public:
bool isPossible(vector<int>& arr, int k, int mid) {
int students = 1, sum = 0;
for (int pages : arr) {
if (pages > mid) return false;
if (sum + pages > mid) {
students++;
sum = pages;
if (students > k) return false;
} else {
sum += pages;
}
}
return true;
}
int findPages(vector<int>& arr, int k) {
int n = arr.size();
if (k > n) return -1;
int low = *max_element(arr.begin(), arr.end());
int high = accumulate(arr.begin(), arr.end(), 0);
int result = high;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isPossible(arr, k, mid)) {
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return result;
}
};