-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAllocate Books.java
More file actions
52 lines (33 loc) · 1.14 KB
/
Allocate Books.java
File metadata and controls
52 lines (33 loc) · 1.14 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
40
41
42
43
44
45
46
47
48
49
50
51
52
//https://www.interviewbit.com/problems/allocate-books/
public class Solution {
public int books(ArrayList<Integer> arr, int M) {
int N = arr.size();
if(N < M)
return -1;
int low = Collections.max(arr);
int high = arr.stream().mapToInt(f -> f.intValue()).sum();
while(low < high){
int mid = low + (high - low)/2;
int students = getCount(arr, mid);
//System.out.println(low + " " + high + " " + students);
if(students <= M)
high = mid;
else
low = mid+1;
}
//low is the answer
return high;
}
public int getCount(ArrayList<Integer> arr, int limit){
int students = 1;
int sum = 0;
for(int val : arr){
if(sum + val > limit){
sum = 0;
students++;
}
sum += val;
}
return students;
}
}