传送带上的包裹必须在 days
天内从一个港口运送到另一个港口。
传送带上的第 i
个包裹的重量为 weights[i]
。每一天,我们都会按给出重量(weights
)的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 days
天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1:
输入:weights = [1,2,3,4,5,6,7,8,9,10], days = 5 输出:15 解释: 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示: 第 1 天:1, 2, 3, 4, 5 第 2 天:6, 7 第 3 天:8 第 4 天:9 第 5 天:10 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], days = 3 输出:6 解释: 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示: 第 1 天:3, 2 第 2 天:2, 4 第 3 天:1, 4
示例 3:
输入:weights = [1,2,3,1,1], days = 4 输出:3 解释: 第 1 天:1 第 2 天:2 第 3 天:3 第 4 天:1, 1
提示:
1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
方法一:二分查找
我们注意到,如果运载能力
我们定义二分查找的左边界
判断是否能在
时间复杂度
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def check(mx):
ws, cnt = 0, 1
for w in weights:
ws += w
if ws > mx:
cnt += 1
ws = w
return cnt <= days
left, right = max(weights), sum(weights) + 1
return left + bisect_left(range(left, right), True, key=check)
class Solution {
public int shipWithinDays(int[] weights, int days) {
int left = 0, right = 0;
for (int w : weights) {
left = Math.max(left, w);
right += w;
}
while (left < right) {
int mid = (left + right) >> 1;
if (check(mid, weights, days)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private boolean check(int mx, int[] weights, int days) {
int ws = 0, cnt = 1;
for (int w : weights) {
ws += w;
if (ws > mx) {
ws = w;
++cnt;
}
}
return cnt <= days;
}
}
class Solution {
public:
int shipWithinDays(vector<int>& weights, int days) {
int left = 0, right = 0;
for (auto& w : weights) {
left = max(left, w);
right += w;
}
auto check = [&](int mx) {
int ws = 0, cnt = 1;
for (auto& w : weights) {
ws += w;
if (ws > mx) {
ws = w;
++cnt;
}
}
return cnt <= days;
};
while (left < right) {
int mid = (left + right) >> 1;
if (check(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
func shipWithinDays(weights []int, days int) int {
var left, right int
for _, w := range weights {
if left < w {
left = w
}
right += w
}
return left + sort.Search(right, func(mx int) bool {
mx += left
ws, cnt := 0, 1
for _, w := range weights {
ws += w
if ws > mx {
ws = w
cnt++
}
}
return cnt <= days
})
}
function shipWithinDays(weights: number[], days: number): number {
let left = 0;
let right = 0;
for (const w of weights) {
left = Math.max(left, w);
right += w;
}
const check = (mx: number) => {
let ws = 0;
let cnt = 1;
for (const w of weights) {
ws += w;
if (ws > mx) {
ws = w;
++cnt;
}
}
return cnt <= days;
};
while (left < right) {
const mid = (left + right) >> 1;
if (check(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}