此处要注意计算天数day的边界控制
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
// 确定范围[minC, maxC], minC是数组中最大元素,maxC是数组累加值
int minC = INT_MIN;
int maxC = 0;
for (auto& weight : weights) {
maxC += weight;
// 注意minC是数组中最大元素
if (weight > minC) minC = weight;
}
int left = minC;
int right = maxC;
while (left <= right) {
int mid = left + (right - left) / 2;
// 注意边界控制
int day = 1;
int cap = mid;
for (int i = 0; i < weights.size(); i++) {
// 若加入当前元素过载,则day++,新增的day算当前开始
if (cap - weights[i] < 0) {
day++;
cap = mid;
}
// 容量减少需要放在判断后面
cap -= weights[i];
if (day > days) {
left = mid + 1;
break;
}
if (i == weights.size() - 1) {
right = mid - 1;
minC = mid;
}
}
}
return minC;
}
};