-
Notifications
You must be signed in to change notification settings - Fork 14
/
Book-Allocation.java
47 lines (43 loc) · 1.38 KB
/
Book-Allocation.java
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
import java.util.*;
public class Main {
public static int countStudents(ArrayList<Integer> arr, int pages) {
int n = arr.size(); // size of array
int students = 1;
long pagesStudent = 0;
for (int i = 0; i < n; i++) {
if (pagesStudent + arr.get(i) <= pages) {
// add pages to current student
pagesStudent += arr.get(i);
} else {
// add pages to next student
students++;
pagesStudent = arr.get(i);
}
}
return students;
}
public static int findPages(ArrayList<Integer> arr, int n, int m) {
// book allocation impossible
if (m > n)
return -1;
int low = Collections.max(arr);
int high = arr.stream().mapToInt(Integer::intValue).sum();
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;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(25, 46, 28, 49, 24));
int n = 5;
int m = 4;
int ans = findPages(arr, n, m);
System.out.println("The answer is: " + ans);
}
}