-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllocateBooks.java
More file actions
42 lines (36 loc) · 1.03 KB
/
AllocateBooks.java
File metadata and controls
42 lines (36 loc) · 1.03 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
package Searching;
public class AllocateBooks {
public static int findPages(int[] arr, int n, int m) {
long sum = 0;
long max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
sum += arr[i];
max = Math.max(max, arr[i]);
}
if (m > n) return -1;
long start = max, end = sum, ans = Integer.MAX_VALUE;
while (start <= end) {
long mid = start + (end - start) / 2;
if (isValid(arr, mid, m)) {
ans = Math.min(ans, mid);
end = mid - 1;
} else {
start = mid + 1;
}
}
return (int) ans;
}
public static boolean isValid(int[] arr, long requiredSum, int m) {
long sum = 0;
int count = 1;
for (int integer : arr) {
if (sum + integer <= requiredSum) {
sum += integer;
} else {
sum = integer;
count++;
}
}
return count <= m;
}
}