Search for a command to run...
Split books so the busiest student reads least
Initialization
Guess a ceiling for how many pages any one student may read, then hand out books in order, starting a new student whenever the next book would breach it. A higher ceiling needs fewer students, so the count is monotonic — the smallest workable ceiling can be binary searched.
Binary Search on the Answer
1function countStudents(nums, pages) {2 const n = nums.length;3 let students = 1;4 let pagesStudent = 0;5 6 for (let i = 0; i < n; i++) {7 // Fits within the current student's ceiling8 if (pagesStudent + nums[i] <= pages) {9 pagesStudent += nums[i];10 } else {11 students++;12 pagesStudent = nums[i];13 }14 }15 return students;//low: 49high: 17216}17 18function findPages(nums, m) {19 const n = nums.length;20 if (m > n) return -1;21 22 let low = Math.max(...nums);23 let high = nums.reduce((a, b) => a + b, 0);24 25 while (low <= high) {26 const mid = Math.floor((low + high) / 2);27 const students = countStudents(nums, mid);28 29 // Too many students needed — raise the ceiling30 if (students > m) {31 low = mid + 1;32 } else {33 high = mid - 1;34 }35 }36 return low;37}