1. Linear Page Limit Increment
Intuition
Loop pages from max(arr) to sum(arr). For each limit, simulate greedy student packing. Return the first limit where students <= m.
When to apply: Basic baseline check.
Algorithm
- Step 1: If m > arr.length return -1.
- Step 2: Loop limit from max(arr) to sum(arr).
- Step 3: If countStudents(limit) <= m return limit.
- Step 4: Return sum(arr).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; int findPages(vector<int>& arr, int k) { if (k > (int)arr.size()) return -1; int low = 0, high = 0; for (int x : arr) { low = max(low, x); high += x; } for (int pages = low; pages <= high; ++pages) { int students = 1, current = 0; for (int x : arr) { if (current + x > pages) { students++; current = 0; } current += x; } if (students <= k) return pages; } return high;} int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * (sum(arr) - max(arr)))— Takes up to sum(arr) iterations of O(n) work each. - Space complexity:
O(1)— O(1) memory.