bookAllocation

int isPossible(vector<int> &arr, int maxPages) {
    int cur = 0;
    int count = 1;

    for (int i = 0; i < arr.size(); i++) {
      if (cur + arr[i] <= maxPages) {
          cur += arr[i];
      } else {
          cur = arr[i];  // we don't want current index's books to be skipped, so we assign them here
          count++;
      }
    }

    return count;
}

int findPages(vector<int>& arr, int n, int m) {
    int maxe = INT_MIN;
    int sum = 0;

    if(m > n)
        return -1;

    for(auto a : arr){
        maxe = max(a,maxe);
        sum +=a; 
    }

    int low = maxe;
    int high = sum;
    int ans = 0;

    while (low <= high) {
        int mid = low + (high-low)/2;

        int students = isPossible(arr, mid);
        if(students > m)
            low = mid+1;
        else{
            high = mid-1;
        }
    }
    return low;
}
  • book allocation -> Allocate books to all students such that number of pages is minimum
  • low = maxPages of a book
  • high = Sum of all pages