-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathalternativePage.java
More file actions
53 lines (46 loc) · 1.24 KB
/
alternativePage.java
File metadata and controls
53 lines (46 loc) · 1.24 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
class Solution {
public static int findPages(int[] arr, int k) {
if (arr.length < k) return -1;
int low = getMax(arr);
int high = getSum(arr);
int result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isPossible(arr, k, mid)) {
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return result;
}
private static int getMax(int[] arr) {
int max = 0;
for (int pages : arr) {
max = Math.max(max, pages);
}
return max;
}
private static int getSum(int[] arr) {
int sum = 0;
for (int pages : arr) {
sum += pages;
}
return sum;
}
private static boolean isPossible(int[] arr, int k, int maxPages) {
int studentsRequired = 1;
int currentSum = 0;
for (int pages : arr) {
if (currentSum + pages > maxPages) {
studentsRequired++;
currentSum = pages;
if (studentsRequired > k) return false;
} else {
currentSum += pages;
}
}
return true;
}
}