forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookAllocation.java
More file actions
69 lines (57 loc) · 2.1 KB
/
BookAllocation.java
File metadata and controls
69 lines (57 loc) · 2.1 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.Scanner;
public class BookAllocation {
public static long findPages(int n, int[] arr, int m) {
// Check if number of students is more than the number of books
if (m > n) return -1;
// Initialize variables
int end = 0;
long ans = 0;
int start = Integer.MIN_VALUE;
// Calculate the total pages (end) and the maximum pages in a single book (start)
for (int i = 0; i < n; i++) {
end += arr[i];
start = Math.max(start, arr[i]);
}
// Perform binary search to find the minimum of the maximum pages
while (start <= end) {
int mid = start + (end - start) / 2;
int pages = 0;
int count = 1;
// Check if current mid value can be used to allocate books
for (int i = 0; i < n; i++) {
pages += arr[i];
if (pages > mid) {
count++;
pages = arr[i];
}
}
// Update the answer based on the number of students required
if (count <= m) {
ans = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Step 1: Input the number of books
System.out.println("Enter the number of books:");
int n = sc.nextInt();
// Step 2: Input the number of pages in each book
int[] arr = new int[n];
System.out.println("Enter the number of pages in each book:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Step 3: Input the number of students
System.out.println("Enter the number of students:");
int m = sc.nextInt();
// Step 4: Find and display the minimum number of maximum pages allocated
long result = findPages(n, arr, m);
System.out.println("Minimum number of maximum pages allocated: " + result);
sc.close();
}
}