-
Notifications
You must be signed in to change notification settings - Fork 0
/
Allocate minimum pages
70 lines (57 loc) · 1.74 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
61
62
63
64
65
66
67
68
69
70
//Allocate minimum pages
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine().trim());
while(tc-- > 0) {
String[] str = br.readLine().trim().split(" ");
int[] a = new int[str.length];
for(int i = 0; i < str.length; i++) {
a[i] = Integer.parseInt(str[i]);
}
String[] nk = br.readLine().trim().split(" ");
int k = Integer.parseInt(nk[0]);
Solution sln = new Solution();
int ans = sln.findPages(a, k);
System.out.println(ans);
System.out.println("~");
}
}
}
class Solution {
public static int findPages(int[] arr, int k) {
if(k > arr.length) {
return -1;
}
int lo = Arrays.stream(arr).max().getAsInt();
int hi = Arrays.stream(arr).sum();
int res = -1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(check(arr, k, mid)){
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
static boolean check(int[] arr, int k, int pageLimit) {
int cnt = 1;
int pageSum = 0;
for(int i = 0; i < arr.length; i++) {
if(pageSum + arr[i] > pageLimit) {
cnt++;
pageSum = arr[i];
}
else {
pageSum += arr[i];
}
}
return (cnt <= k);
}
}