LeetCode 题解工作台

拥有最多糖果的孩子

有 n 个有糖果的孩子。给你一个数组 candies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目,和一个整数 extraCandies 表示你所有的额外糖果的数量。 返回一个长度为 n 的布尔数组 result ,如果把所有的 extraCandies 给第 i 个孩子之后,他会…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有 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.length
  • 2 <= n <= 100
  • 1 <= candies[i] <= 100
  • 1 <= extraCandies <= 50
lightbulb

解题思路

方法一

1
2
3
4
5
class Solution:
    def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
        mx = max(candies)
        return [candy + extraCandies >= mx for candy in candies]
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

拥有最多糖果的孩子题解:数组·driven | LeetCode #1431 简单