this is the code
#include <bits/stdc++.h>
using namespace std;
bool check(long long int *a, long long int students, long long int books, long long int n) {
int c = 1;
long long int total = 0;
for(int i = 0; i < n; i++) {
if(total + a[i] > books) {
c++;
total = a[i];
if(c > students) {
return false;
}
}
else {
total = total + a[i];
}
}
return true;
}
int main() {
long long int n, students;
cin >> n >> students;
long long int a[n];
long long int sum = 0;
for(int i = 0; i < n; i++) {
cin >> a[i];
sum = sum + a[i];
}
if(n < students) {
cout << "-1";
return 0;
}
long long int s = 0;
long long int e = sum;
long long int ans = INT_MAX;
while(s <= e) {
long long int mid = (s+e)/2;
bool pdlega = check(a, students, mid, n);
if(pdlega) {
ans = min(ans, mid);
e = mid - 1;
}
else {
s = mid + 1;
}
}
cout << ans << endl;
}