-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathAllocateBooks.java
More file actions
76 lines (56 loc) · 1.35 KB
/
AllocateBooks.java
File metadata and controls
76 lines (56 loc) · 1.35 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package BinarySearch;
import java.util.ArrayList;
/**
* Author - archit.s
* Date - 03/10/18
* Time - 11:41 PM
*/
public class AllocateBooks {
int getMax(ArrayList<Integer> A){
int max = A.get(0);
for(int i=1;i<A.size();i++){
if(A.get(i) > max){
max = A.get(i);
}
}
return max;
}
int getSum(ArrayList<Integer> A){
int sum = 0;
for(int i=0;i<A.size();i++){
sum += A.get(i);
}
return sum;
}
int numberOfBooks(ArrayList<Integer> A, int maxLen){
int totalLen = 0;
int number = 1;
for(int i=0;i<A.size();i++){
totalLen += A.get(i);
if(totalLen > maxLen){
number++;
totalLen = A.get(i);
}
}
return number;
}
public int books(ArrayList<Integer> A, int B) {
if(B > A.size()){
return -1;
}
int low = getMax(A);
int high = getSum(A);
long sol = Integer.MAX_VALUE;
while(low <= high){
int mid = low + (high-low)/2;
if(numberOfBooks(A,mid) <= B){
sol = Math.min(mid, sol);
high = mid-1;
}
else{
low = mid+1;
}
}
return (int)sol;
}
}