[InterviewBit] Allocate Books

Allocate Books

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool helper(vector<int>& A, long long mi, long long B) {
long long now = 0, count = 1;
for(int i = 0; i < A.size(); i++) {
if(now + A[i] <= mi) now += A[i];
else now = A[i], count += 1;
}
return count <= B;
}
int Solution::books(vector<int> &A, int B) {
if(A.size() < B) return -1;
long long l = *max_element(begin(A), end(A)), r = INT_MAX, res = INT_MAX;
while(l <= r) {
long long m = l + (r - l) / 2;
bool pass = helper(A,m,B);
if(pass) {
r = m - 1;
res = m;
} else l = m + 1;
}
return res == INT_MAX ? -1 : res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/06/PS/interviewbit/allocate-books/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.