-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAllocate Minimum Pages
60 lines (43 loc) · 1.62 KB
/
Allocate Minimum Pages
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
/** You are given an array arr[] of integers, where each element arr[i] represents the number of pages in the ith book. You also have an integer k representing the number of students. The task is to allocate books to each student such that:
>>> Each student receives atleast one book.
>>> Each student is assigned a contiguous sequence of books.
>>> No book is assigned to more than one student.
>>> The objective is to minimize the maximum number of pages assigned to any student. In other words, out of all possible allocations, find the arrangement where the student who receives the most pages still has the smallest possible maximum.
Note: Return -1 if a valid assignment is not possible, and allotment should be in contiguous order (see the explanation for better understanding).
**/
// JAVA CODE
class Solution {
static boolean isPossible(int arr[],int k,int mid)
{
int sum=0,student=1;
for(int x:arr)
{
sum+=x;
if(sum>mid)
{
student++;
sum=x;
}
}
return student<=k;
}
public static int findPages(int[] arr, int k)
{
if(k>arr.length)return -1;
int sum = 0,mx=Integer.MIN_VALUE;
for(int x:arr){
sum+=x;
mx=Math.max(mx,x);
}
int low=mx,high=sum,mid,ans=Integer.MAX_VALUE;
while(low<=high){
mid=(low+high)/2;
if(isPossible(arr,k,mid)){
high=mid-1;
ans=Math.min(ans,mid);
}
else low=mid+1;
}
return ans;
}
}