-
Notifications
You must be signed in to change notification settings - Fork 654
/
allocateBooksJava
42 lines (41 loc) · 1.2 KB
/
allocateBooksJava
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
public class Solution {
private boolean isPossible(ArrayList<Integer> A, int pages, int students) {
int cnt = 0;
int sumAllocated = 0;
for(int i = 0;i<A.size();i++) {
if(sumAllocated + A.get(i) > pages) {
cnt++;
sumAllocated = A.get(i);
if(sumAllocated > pages) return false;
}
else {
sumAllocated += A.get(i);
}
}
if(cnt < students) return true;
return false;
}
public int books(ArrayList<Integer> A, int B) {
if(B > A.size()) return -1;
int low = A.get(0);
int high = 0;
for(int i = 0;i<A.size();i++) {
high = high + A.get(i);
low = Math.min(low, A.get(i));
}
int res = -1;
while(low <= high) {
int mid = (low + high) >> 1;
//cout << low << " " << high << " " << mid << endl;
if(isPossible(A, mid, B)) {
res = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}
// return res -> this is also correct
return low;
}
}