#include <iostream> using namespace std; bool allocationIsPossible(int arr[], int n, int m, int mid) { int sum = 0; int studentCount = 1; for (int i = 0; i < n; i++) { if (sum + arr[i] <= mid) { sum += arr[i]; } else { studentCount++; if (studentCount > m || arr[i] > mid) { return false; } sum = arr[i]; } } return true; } int bookAllocate(int arr[], int n, int m) { int start = 0; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } int end = sum; int mid = start + (end - start) / 2; int ans = -1; while (start <= end) { if (allocationIsPossible(arr, n, m, mid)) { ans = mid; end = mid - 1; } else { start = mid + 1; } mid = start + (end - start) / 2; } return ans; } int main() { int arr[4] = {10, 20, 30, 40}; int ans = bookAllocate(arr, 4, 2); cout << "Minimum pages: " << ans << endl; return 0; } // output is 60
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter