LeetCode 题解工作台
平衡装运的最大数量
给你一个长度为 n 的整数数组 weight ,表示按直线排列的 n 个包裹的重量。 装运 定义为包裹的一个连续子数组。如果一个装运满足以下条件,则称其为 平衡装运 : 最后一个包裹的重量 严格小于 该装运中所有包裹中 最大重量 。 选择若干个 不重叠 的连续平衡装运,并满足 每个包裹最多出现在一次…
0
题型
5
代码语言
0
相关题
当前训练重点
中等 · Maximum Balanced Shipments core interview pattern
答案摘要
我们维护当前遍历的数组的最大值 ,并遍历数组中的每个元素 。如果 $x < \text{mx}$,则说明当前元素可以作为一个平衡装运的最后一个包裹,因此我们就将答案加一,并将 重置为 0。否则,我们更新 为当前元素 的值。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Maximum Balanced Shipments core interview pattern 题型思路
题目描述
给你一个长度为 n 的整数数组 weight,表示按直线排列的 n 个包裹的重量。装运 定义为包裹的一个连续子数组。如果一个装运满足以下条件,则称其为 平衡装运:最后一个包裹的重量 严格小于 该装运中所有包裹中 最大重量 。
选择若干个 不重叠 的连续平衡装运,并满足 每个包裹最多出现在一次装运中(部分包裹可以不被装运)。
返回 可以形成的平衡装运的最大数量 。
示例 1:
输入: weight = [2,5,1,4,3]
输出: 2
解释:
我们可以形成最多两个平衡装运:
- 装运 1:
[2, 5, 1]- 包裹的最大重量 = 5
- 最后一个包裹的重量 = 1,严格小于 5,因此这是平衡装运。
- 装运 2:
[4, 3]- 包裹的最大重量 = 4
- 最后一个包裹的重量 = 3,严格小于 4,因此这是平衡装运。
无法通过其他方式划分包裹获得超过两个平衡装运,因此答案是 2。
示例 2:
输入: weight = [4,4]
输出: 0
解释:
在这种情况下无法形成平衡装运:
- 装运
[4, 4]的最大重量为 4,而最后一个包裹的重量也是 4,不严格小于最大重量,因此不是平衡的。 - 单个包裹的装运
[4]中,最后一个包裹的重量等于最大重量,因此也不是平衡的。
由于无法形成任何平衡装运,答案是 0。
提示:
2 <= n <= 1051 <= weight[i] <= 109
解题思路
方法一:贪心
我们维护当前遍历的数组的最大值 ,并遍历数组中的每个元素 。如果 ,则说明当前元素可以作为一个平衡装运的最后一个包裹,因此我们就将答案加一,并将 重置为 0。否则,我们更新 为当前元素 的值。
遍历结束后,返回答案即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 ,只使用了常数级别的额外空间。
class Solution:
def maxBalancedShipments(self, weight: List[int]) -> int:
ans = mx = 0
for x in weight:
mx = max(mx, x)
if x < mx:
ans += 1
mx = 0
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate uses a monotonic stack to efficiently find valid subarrays.
- question_mark
The candidate demonstrates an understanding of greedy algorithms for partitioning.
- question_mark
The candidate ensures no overlapping parcels in the selected shipments.
常见陷阱
外企场景- error
Failing to account for parcels that are unshipped.
- error
Not ensuring the shipment balance condition holds (last parcel being less than max weight).
- error
Using an inefficient brute force approach, leading to time limit issues.
进阶变体
外企场景- arrow_right_alt
Variation 1: Handle edge cases like when there are only two parcels or when all parcels have the same weight.
- arrow_right_alt
Variation 2: Modify the problem to allow a partial shipment, i.e., shipments that do not need to be contiguous.
- arrow_right_alt
Variation 3: Change the weight constraint, making parcels weigh much more or less, affecting the balance condition.