-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookAllocation.java
More file actions
73 lines (62 loc) · 1.51 KB
/
BookAllocation.java
File metadata and controls
73 lines (62 loc) · 1.51 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
public class BookAllocation {
public static void main(String[] args)
{
int[] arr = {2,8,8,4,5};
int noS = 6;
int allocationResult = allocate(arr, noS);
if(noS > arr.length)
{
allocationResult = -1;
}
System.out.println(allocationResult);
}
private static int allocate(int[] arr, int noS)
{
int s = 0;
int sum = 0;
for(int i:arr)
{
sum += i;
}
int e = sum;
int mid = s + (e - s)/2;
int ans = -1;
while(s <= e)
{
if(ifPossible(arr, noS, mid))
{
ans = mid;
e = mid - 1;
}
else
{
s = mid + 1;
}
mid = s + (e - s)/2;
}
return ans;
}
private static boolean ifPossible(int[] arr, int noS, int mid)
{
int studentCount = 1;
int pagesCount = 0;
for(int i=0; i<arr.length; i++)
{
if((pagesCount + arr[i]) <= mid)
{
pagesCount += arr[i];
}
else
{
studentCount++;
if(studentCount > noS || pagesCount > mid)
{
return false;
}
pagesCount = 0;
pagesCount = arr[i];
}
}
return true;
}
}