LeetCode 题解工作台
雪糕的最大数量
夏日炎炎,小男孩 Tony 想买一些雪糕消消暑。 商店中新到 n 支雪糕,用长度为 n 的数组 costs 表示雪糕的定价,其中 costs[i] 表示第 i 支雪糕的现金价格。Tony 一共有 coins 现金可以用于消费,他想要买尽可能多的雪糕。 注意: Tony 可以按任意顺序购买雪糕。 给你…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
要买尽可能多的雪糕,且可以按任意顺序购买,因此,我们应该优先选择定价小的雪糕。 对数组 `costs` 进行排序,然后从定价最小的雪糕开始,依次购买,直到不能购买为止,返回能购买的雪糕数量。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
夏日炎炎,小男孩 Tony 想买一些雪糕消消暑。
商店中新到 n 支雪糕,用长度为 n 的数组 costs 表示雪糕的定价,其中 costs[i] 表示第 i 支雪糕的现金价格。Tony 一共有 coins 现金可以用于消费,他想要买尽可能多的雪糕。
注意:Tony 可以按任意顺序购买雪糕。
给你价格数组 costs 和现金量 coins ,请你计算并返回 Tony 用 coins 现金能够买到的雪糕的 最大数量 。
你必须使用计数排序解决此问题。
示例 1:
输入:costs = [1,3,2,4,1], coins = 7 输出:4 解释:Tony 可以买下标为 0、1、2、4 的雪糕,总价为 1 + 3 + 2 + 1 = 7
示例 2:
输入:costs = [10,6,8,7,7,8], coins = 5 输出:0 解释:Tony 没有足够的钱买任何一支雪糕。
示例 3:
输入:costs = [1,6,3,1,2,5], coins = 20 输出:6 解释:Tony 可以买下所有的雪糕,总价为 1 + 6 + 3 + 1 + 2 + 5 = 18 。
提示:
costs.length == n1 <= n <= 1051 <= costs[i] <= 1051 <= coins <= 108
解题思路
方法一:贪心 + 排序
要买尽可能多的雪糕,且可以按任意顺序购买,因此,我们应该优先选择定价小的雪糕。
对数组 costs 进行排序,然后从定价最小的雪糕开始,依次购买,直到不能购买为止,返回能购买的雪糕数量。
时间复杂度 ,空间复杂度 。其中 是数组 costs 的长度。
class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
costs.sort()
for i, c in enumerate(costs):
if coins < c:
return i
coins -= c
return len(costs)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log n) with standard sort, or O(n + maxCost) with counting sort. Space complexity is O(n) for sorting or O(maxCost) for counting array. Iteration is O(n) in all cases. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask how to maximize purchases without overspending coins.
- question_mark
Check if candidate recognizes greedy choice invariant with costs.
- question_mark
Probe if counting sort can optimize large inputs efficiently.
常见陷阱
外企场景- error
Failing to sort costs before greedy selection leads to suboptimal purchases.
- error
Attempting to pick bars in arbitrary order can exceed coins early.
- error
Ignoring large cost values and limits may cause inefficiency or overflow.
进阶变体
外企场景- arrow_right_alt
Compute maximum bars if each bar has a limit on quantity available.
- arrow_right_alt
Determine maximum bars with a dynamic coin replenishment after each purchase.
- arrow_right_alt
Maximize bars when only contiguous subarrays of costs can be purchased.