DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Allocate minimum pages

Allocate minimum pages

class Solution {
    public int findPages(int[] arr, int k) {
        if(k> arr.length) return -1;
        // code here
        int min = arr[0];
        int max = 0;
        for(int i: arr){
            max+=i;
            min = Math.max(min, i);// min should be such that it is the max vaule of the arr 
            //othewise if arr[i] > min then that book can not be assigned to a single 
            //student and we can not partially assign 1 book to 2 students
        }
        int result = -1;

        while(min<=max){
            int mid = (min+max)/2;
            if(isPossible(mid, arr, k)){
                result = mid;
                max = mid-1;
            }
            else min = mid+1;
        }
        return result;
    }

    public boolean isPossible(int minPage, int [] arr, int k){
        int noOfStudents  = 1; //one student will satisfy the condition 
        int currentPage = 0;
        for(int pages : arr){
            //per student max pages(currentPage+pages) assigned should be less than or equal to minPage else we will to assign
            // that pages(i.e arr[i] to the next student) 
            if(pages + currentPage > minPage){
                currentPage =0; //reset the currentPage for the new student
                noOfStudents++;
            }
            currentPage+=pages;// currentPage will initialize with the current ith page i.e pages here 
        }
        return noOfStudents<=k;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)