LeetCode 题解工作台
K 件物品的最大和
袋子中装有一些物品,每个物品上都标记着数字 1 、 0 或 -1 。 给你四个非负整数 numOnes 、 numZeros 、 numNegOnes 和 k 。 袋子最初包含: numOnes 件标记为 1 的物品。 numZeros 件标记为 0 的物品。 numNegOnes 件标记为 -1 …
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
根据题目描述,我们应该尽可能多地取标记为 的物品,然后取标记为 的物品,最后取标记为 的物品。 因此:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
袋子中装有一些物品,每个物品上都标记着数字 1 、0 或 -1 。
给你四个非负整数 numOnes 、numZeros 、numNegOnes 和 k 。
袋子最初包含:
numOnes件标记为1的物品。numZeros件标记为0的物品。numNegOnes件标记为-1的物品。
现计划从这些物品中恰好选出 k 件物品。返回所有可行方案中,物品上所标记数字之和的最大值。
示例 1:
输入:numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2
输出:2
解释:袋子中的物品分别标记为 {1, 1, 1, 0, 0} 。取 2 件标记为 1 的物品,得到的数字之和为 2 。
可以证明 2 是所有可行方案中的最大值。
示例 2:
输入:numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
输出:3
解释:袋子中的物品分别标记为 {1, 1, 1, 0, 0} 。取 3 件标记为 1 的物品,1 件标记为 0 的物品,得到的数字之和为 3 。
可以证明 3 是所有可行方案中的最大值。
提示:
0 <= numOnes, numZeros, numNegOnes <= 500 <= k <= numOnes + numZeros + numNegOnes
解题思路
方法一:贪心
根据题目描述,我们应该尽可能多地取标记为 的物品,然后取标记为 的物品,最后取标记为 的物品。
因此:
- 如果袋子中的物品标记为 的数量大于等于 ,那么取 件物品,数字之和为 ;
- 如果袋子中的物品标记为 的数量小于 ,那么取 件物品,数字之和为 ;如果标记为 的物品数量大于等于 ,那么再取 件物品,数字之和还是 ;
- 否则,我们再从标记为 的物品中取 件物品,数字之和为 。
时间复杂度 ,空间复杂度 。
class Solution:
def kItemsWithMaximumSum(
self, numOnes: int, numZeros: int, numNegOnes: int, k: int
) -> int:
if numOnes >= k:
return k
if numZeros >= k - numOnes:
return numOnes
return numOnes - (k - numOnes - numZeros)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity are O(1) because the algorithm involves simple arithmetic and comparisons based on counts rather than iterating over all items. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect candidate to identify the greedy priority of 1 > 0 > -1.
- question_mark
Look for proper handling of k exceeding available 1s and 0s.
- question_mark
Candidate should reason about maintaining sum invariance at each choice.
常见陷阱
外企场景- error
Assuming the items must be iterated individually instead of using counts.
- error
Forgetting to handle cases where k exceeds numOnes and numZeros.
- error
Misapplying the greedy order and picking -1s too early.
进阶变体
外企场景- arrow_right_alt
Generalizing to items with arbitrary positive, zero, and negative integers.
- arrow_right_alt
Changing k dynamically and recalculating maximum sum quickly.
- arrow_right_alt
Allowing repeated items and selecting with replacement constraints.