[InterviewBit] Capacity To Ship Packages Within B Days

Capacity To Ship Packages Within B Days

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int helper(vector<int>& A, int k) {
int res = 1, now = 0;
for(auto a : A) {
if(now + a > k) {
now = a;
res += 1;
} else now += a;
}
return res;
}
int Solution::solve(vector<int> &A, int B) {
int l = *max_element(begin(A), end(A)), r = INT_MAX, res = INT_MAX;
while(l <= r) {
int m = l + (r - l) / 2;
int d = helper(A,m);
if(d <= B) res = min(res, m);
if(d > B) l = m + 1;
else r = m - 1;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/15/PS/interviewbit/capacity-to-ship-packages-within-b-days/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.