TikTok VO 面试真题解析:在 D 天内运完包裹的最小船运容量

20次阅读
没有评论

You are given a series of packages arranged on a conveyor belt. Each package has a specific weight, represented by the array weights, where the ith element indicates the weight of the ith package. These packages must be transported from one location to another within a specified number of days, denoted as days.

Every day, the ship can be loaded with one or more consecutive packages from the belt, but the total weight loaded on any single day must not exceed the ship’s maximum weight capacity. Packages must be shipped in the order they appear; no reordering is allowed.

Your task is to determine the minimum possible weight capacity the ship must have so that all the packages can be shipped within the given number of days.

Example 1:

Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15

Example 2:

Input: weights = [3,2,2,4,1,4], days = 3
Output: 6

Example 3:

Input: weights = [1,2,3,1,1], days = 4
Output: 3

这道题的核心是“最小化最大值”:在不改变包裹顺序的前提下,把连续包裹分配到若干天中,求能在指定天数内完成运输的最小船运容量。常见做法是对容量进行二分搜索,容量下界是单个包裹的最大重量,上界是所有包裹重量之和;每次用贪心模拟按顺序装载,统计在当前容量下需要几天,如果天数超标就增大容量,否则缩小容量。由于单调性非常明显,这种二分 + 贪心的方式通常能高效求解。

正文完
 0