LeetCode 题解工作台
卡车上的最大单元数
请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxes i , numberOfUnitsPerBox i ] : numberOfBoxes i 是类型 i 的箱子的数量。 numberOfUnitsPerBox i …
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
根据题意,我们应该选择尽可能多的单元数,因此,我们先对 `boxTypes` 按照单元数从大到小的顺序排列。 然后从前往后遍历 `boxTypes`,选择最多 `truckSize` 个箱子,累加单元数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi] :
numberOfBoxesi是类型i的箱子的数量。numberOfUnitsPerBoxi是类型i每个箱子可以装载的单元数量。
整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。
返回卡车可以装载 单元 的 最大 总数。
示例 1:
输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 输出:8 解释:箱子的情况如下: - 1 个第一类的箱子,里面含 3 个单元。 - 2 个第二类的箱子,每个里面含 2 个单元。 - 3 个第三类的箱子,每个里面含 1 个单元。 可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8
示例 2:
输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 输出:91
提示:
1 <= boxTypes.length <= 10001 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 10001 <= truckSize <= 106
解题思路
方法一:贪心 + 排序
根据题意,我们应该选择尽可能多的单元数,因此,我们先对 boxTypes 按照单元数从大到小的顺序排列。
然后从前往后遍历 boxTypes,选择最多 truckSize 个箱子,累加单元数。
时间复杂度 ,其中 表示二维数组 boxTypes 的长度。
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
ans = 0
for a, b in sorted(boxTypes, key=lambda x: -x[1]):
ans += b * min(truckSize, a)
truckSize -= a
if truckSize <= 0:
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) due to sorting, where n is the number of box types. Space complexity is O(1) extra space if sorting in place, otherwise O(n). Iteration over box types is linear, O(n). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Mentions prioritizing boxes with higher units per box.
- question_mark
Asks how to handle remaining truck capacity after partial selection of a box type.
- question_mark
Looks for proof that greedy selection guarantees maximum units.
常见陷阱
外企场景- error
Failing to sort by units per box, leading to suboptimal total units.
- error
Ignoring the truckSize limit when adding boxes, which breaks constraints.
- error
Adding boxes of a lower-unit type before exhausting higher-unit types.
进阶变体
外企场景- arrow_right_alt
Maximize total units with multiple trucks each with different capacities.
- arrow_right_alt
Boxes have weights and units; maximize units without exceeding truck weight limit.
- arrow_right_alt
Box types may have expiration or priority constraints affecting loading order.