LeetCode 题解工作台
你能在你最喜欢的那天吃到你最喜欢的糖果吗?
给你一个下标从 0 开始的正整数数组 candiesCount ,其中 candiesCount[i] 表示你拥有的第 i 类糖果的数目。同时给你一个二维数组 queries ,其中 queries[i] = [favoriteType i , favoriteDay i , dailyCap i …
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 前缀和
答案摘要
时间复杂度 ,空间复杂度 。其中 为数组 `candiesCount` 的长度。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个下标从 0 开始的正整数数组 candiesCount ,其中 candiesCount[i] 表示你拥有的第 i 类糖果的数目。同时给你一个二维数组 queries ,其中 queries[i] = [favoriteTypei, favoriteDayi, dailyCapi] 。
你按照如下规则进行一场游戏:
- 你从第
0天开始吃糖果。 - 你在吃完 所有 第
i - 1类糖果之前,不能 吃任何一颗第i类糖果。 - 在吃完所有糖果之前,你必须每天 至少 吃 一颗 糖果。
请你构建一个布尔型数组 answer ,用以给出 queries 中每一项的对应答案。此数组满足:
answer.length == queries.length。answer[i]是queries[i]的答案。answer[i]为true的条件是:在每天吃 不超过dailyCapi颗糖果的前提下,你可以在第favoriteDayi天吃到第favoriteTypei类糖果;否则answer[i]为false。
注意,只要满足上面 3 条规则中的第二条规则,你就可以在同一天吃不同类型的糖果。
请你返回得到的数组 answer 。
示例 1:
输入:candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]] 输出:[true,false,true] 提示: 1- 在第 0 天吃 2 颗糖果(类型 0),第 1 天吃 2 颗糖果(类型 0),第 2 天你可以吃到类型 0 的糖果。 2- 每天你最多吃 4 颗糖果。即使第 0 天吃 4 颗糖果(类型 0),第 1 天吃 4 颗糖果(类型 0 和类型 1),你也没办法在第 2 天吃到类型 4 的糖果。换言之,你没法在每天吃 4 颗糖果的限制下在第 2 天吃到第 4 类糖果。 3- 如果你每天吃 1 颗糖果,你可以在第 13 天吃到类型 2 的糖果。
示例 2:
输入:candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]] 输出:[false,true,true,false,false]
提示:
1 <= candiesCount.length <= 1051 <= candiesCount[i] <= 1051 <= queries.length <= 105queries[i].length == 30 <= favoriteTypei < candiesCount.length0 <= favoriteDayi <= 1091 <= dailyCapi <= 109
解题思路
方法一:前缀和
时间复杂度 ,空间复杂度 。其中 为数组 candiesCount 的长度。
class Solution:
def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:
s = list(accumulate(candiesCount, initial=0))
ans = []
for t, day, mx in queries:
least, most = day, (day + 1) * mx
ans.append(least < s[t + 1] and most > s[t])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to understand array manipulation and prefix sum optimization.
- question_mark
Knowledge of binary search and how to apply it in practical problems.
- question_mark
Strong understanding of time complexity and its application in large input sizes.
常见陷阱
外企场景- error
Misunderstanding the role of the dailyCap constraint and not checking it properly for each query.
- error
Forgetting to use prefix sum for efficient range calculations.
- error
Not optimizing for large inputs, resulting in time limit exceeded errors due to inefficient approaches.
进阶变体
外企场景- arrow_right_alt
What if the `candiesCount` array had more types of candies? Consider how the solution scales.
- arrow_right_alt
How does the problem change if we introduce variable daily caps instead of a fixed one?
- arrow_right_alt
What if we need to handle queries with a wider range of favorite days or candy types?