LeetCode 题解工作台
拥有最多糖果的孩子
有 n 个有糖果的孩子。给你一个数组 candies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目,和一个整数 extraCandies 表示你所有的额外糖果的数量。 返回一个长度为 n 的布尔数组 result ,如果把所有的 extraCandies 给第 i 个孩子之后,他会…
1
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
有 n 个有糖果的孩子。给你一个数组 candies,其中 candies[i] 代表第 i 个孩子拥有的糖果数目,和一个整数 extraCandies 表示你所有的额外糖果的数量。
返回一个长度为 n 的布尔数组 result,如果把所有的 extraCandies 给第 i 个孩子之后,他会拥有所有孩子中 最多 的糖果,那么 result[i] 为 true,否则为 false。
注意,允许有多个孩子同时拥有 最多 的糖果数目。
示例 1:
输入:candies = [2,3,5,1,3], extraCandies = 3 输出:[true,true,true,false,true] 解释:如果你把额外的糖果全部给: 孩子 1,将有 2 + 3 = 5 个糖果,是孩子中最多的。 孩子 2,将有 3 + 3 = 6 个糖果,是孩子中最多的。 孩子 3,将有 5 + 3 = 8 个糖果,是孩子中最多的。 孩子 4,将有 1 + 3 = 4 个糖果,不是孩子中最多的。 孩子 5,将有 3 + 3 = 6 个糖果,是孩子中最多的。
示例 2:
输入:candies = [4,2,1,1,2], extraCandies = 1 输出:[true,false,false,false,false] 解释:只有 1 个额外糖果,所以不管额外糖果给谁,只有孩子 1 可以成为拥有糖果最多的孩子。
示例 3:
输入:candies = [12,1,12], extraCandies = 10 输出:[true,false,true]
提示:
n == candies.length2 <= n <= 1001 <= candies[i] <= 1001 <= extraCandies <= 50
解题思路
方法一
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
mx = max(candies)
return [candy + extraCandies >= mx for candy in candies]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate identify an array-driven solution strategy?
- question_mark
Is the candidate able to recognize when an approach involves comparing elements in an array?
- question_mark
Does the candidate optimize the solution to avoid unnecessary recalculations?
常见陷阱
外企场景- error
Failing to find the maximum value before comparing each kid's total with extraCandies.
- error
Not understanding the requirement that multiple kids can have the greatest number of candies.
- error
Mistaking the problem as requiring sorting, when it can be solved with a simple comparison.
进阶变体
外企场景- arrow_right_alt
Consider varying the number of kids or the size of extraCandies.
- arrow_right_alt
What if extraCandies were negative or zero?
- arrow_right_alt
How would the solution change if we needed to find kids who would not have the greatest number of candies?