Allocate minimum number of pages | Utility method to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ; increment student count ; update curr_sum ; if students required becomes greater than given no . of students , return false ; else update curr_sum ; method to find minimum pages ; return - 1 if no . of books is less than no . of students ; Count total number of pages ; initialize start as 0 pages and end as total pages ; traverse until start <= end ; check if it is possible to distribute books by using mid as current minimum ; if yes then find the minimum distribution ; as we are finding minimum and books are sorted so reduce end = mid - 1 that means ; if not possible means pages should be increased so update start = mid + 1 ; at - last return minimum no . of pages ; Number of pages in books ; let m = 2 ; No . of students
function isPossible ( arr , n , m , curr_min ) { let studentsRequired = 1 ; let curr_sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > curr_min ) return false ; if ( curr_sum + arr [ i ] > curr_min ) { studentsRequired ++ ; curr_sum = arr [ i ] ; if ( studentsRequired > m ) return false ; } else curr_sum += arr [ i ] ; } return true ; } function findPages ( arr , n , m ) { let sum = 0 ; if ( n < m ) return - 1 ; for ( let i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; let start = 0 , end = sum ; let result = Number . MAX_VALUE ; while ( start <= end ) { let mid = Math . floor ( ( start + end ) / 2 ) ; if ( isPossible ( arr , n , m , mid ) ) { result = Math . min ( result , mid ) ; end = mid - 1 ; } else start = mid + 1 ; } return result ; } let arr = [ 12 , 34 , 67 , 90 ] ; document . write ( " " + findPages ( arr , arr . length , m ) ) ;