forked from keshavagarwal17/All-Cp-Algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallocate_minimum_number_of_pages.java
71 lines (64 loc) · 1.3 KB
/
allocate_minimum_number_of_pages.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.*;
import java.util.*;
class pages {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int m=sc.nextInt();
Solution ob = new Solution();
System.out.println(ob.findPages(a,n,m));
}
}
}// } Driver Code Ends
//User function Template for Java
class Solution
{
//Function to find minimum number of pages.
public static int findPages(int[]a,int n,int m)
{ if(n<m)
return -1;
int sum = 0;
for(int i = 0;i<n;i++)
sum += a[i];
int s = 0,e = sum;
int res = 0;
while(s<=e)
{
int mid = s+(e-s)/2;
if(possible(a,n,m,mid))
{
res = mid;
e = mid-1;
}
else
s = mid+1;
}
return res;
}
public static boolean possible(int a[],int n,int m,int mid)
{ int s = 1;
int sum = 0;
for(int i = 0;i<n;i++)
{
if(a[i]>mid)
return false;
if(sum+a[i]>mid)
{ s++;
sum = a[i];
if(s>m)
return false;
}
else
sum+= a[i];
}
return true;
}
};