From 2f7bdd496552ba3f4427223d3ace3be57bc94ee3 Mon Sep 17 00:00:00 2001 From: kritipct <109505506+kritipct@users.noreply.github.com> Date: Mon, 10 Oct 2022 13:17:00 +0530 Subject: [PATCH] Added famous book allocation problem --- Book_Allocation.java | 84 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Book_Allocation.java diff --git a/Book_Allocation.java b/Book_Allocation.java new file mode 100644 index 00000000..6c2b2977 --- /dev/null +++ b/Book_Allocation.java @@ -0,0 +1,84 @@ +//Problem : https://www.geeksforgeeks.org/allocate-minimum-number-pages/ + +// Java program for optimal allocation of pages + +public class Book_Allocation { + // Utility method to check if current minimum value + // is feasible or not. + static boolean isPossible(int arr[], int n, int m, + int curr_min) + { + int studentsRequired = 1; + int curr_sum = 0; + + // iterate over all books + for (int i = 0; i < n; i++) { + curr_sum += arr[i]; + if (curr_sum > curr_min) { + studentsRequired++; // increment student + // count + + curr_sum = arr[i]; // update curr_sum + } + } + + return studentsRequired <= m; + } + + // method to find minimum pages + static int findPages(int arr[], int n, int m) + { + int sum = 0; + + // return -1 if no. of books is less than + // no. of students + if (n < m) + return -1; + + // Count total number of pages + for (int i = 0; i < n; i++) + sum += arr[i]; + + // initialize start as arr[n-1] pages(minimum answer + // possible) and end as total pages(maximum answer + // possible) + int start = arr[n - 1], end = sum; + int result = Integer.MAX_VALUE; + + // traverse until start <= end + while (start <= end) { + // check if it is possible to distribute + // books by using mid is current minimum + int mid = start + (end - start) / 2; + if (isPossible(arr, n, m, mid)) { + // update result to current distribution + // as it's the best we have found till now. + result = mid; + + // as we are finding minimum so, + end = mid - 1; + } + + else + // if not possible, means pages should be + // increased ,so update start = mid + 1 + start = mid + 1; + } + + // at-last return minimum no. of pages + return result; + } + + // Driver Method + public static void main(String[] args) + { + + int arr[] = { 12, 34, 67, + 90 }; // Number of pages in books + + int m = 2; // No. of students + + System.out.println("Minimum number of pages = " + + findPages(arr, arr.length, m)); + } +}