I tried to solve this problem with my own code and it was giving correct output for two test-cases. But when I submit in hackerblocks, none of the test-cases pass? Please help me find the bug in my code!
#include<bits/stdc++.h>
using namespace std;
bool isPossible(int books[], int n, int m, int pages) {
int student = 0;
int cnt = 1;
for (int i = 0; i < n; i++) {
student += books[i];
if (student <= pages && cnt <= m) {
if (cnt == m && i == n - 1) {
return true;
}
}
else if (cnt > m)
return false;
else {
cnt++;
student = 0;
i–;
}
}
return false;
}
int main() {
int t; cin>>t;
while(t–){
int n, m;
cin >> n >> m;
int books[n];
int sum = 0;
for (int i = 0; i < n; i++) {
cin >> books[i];
sum += books[i];
}
// Binary search - search space to be defined by you
int s = books[n - 1];
int e = sum;
int ans = INT_MAX;
while (s <= e) {
int mid = (s + e) / 2;
bool maxpage = isPossible(books, n, m, mid);
if (maxpage) {
ans = min(ans, mid);
e = mid - 1;
}
else
s = mid + 1;
}
cout << ans;
}
}