LeetCode 1011. Capacity To Ship Packages Within D Days

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int shipWithinDays(vector<int>& weights, int D) {
int left = *max_element(weights.begin(), weights.end()),
right = accumulate(weights.begin(), weights.end(), 0);
while (left < right) {
int mid = (left + right) / 2;
int dayCnt = 1, curr = 0;
for (const auto& w : weights) {
if (curr + w > mid) {
++dayCnt;
curr = 0;
}
curr += w;
}
if (dayCnt <= D) right = mid;
else left = mid + 1;
}
return left;
}
};