Kids With the Greatest Number of Candies
There are n kids with candies. You are given an array candies where candiesi represents the number of candies the i-th kid has, and an integer extraCandies representing the number of extra candies you have. Return a boolean array result where resulti is true if, after giving the i-th kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise. More than one kid can have the greatest number of candies at the same time. Find the current maximum once, then check each kid against it plus the extra.
Constraints
- n == candies.length
- 2 ≤ n ≤ 100
- 1 ≤ candiesi ≤ 100
- 1 ≤ extraCandies ≤ 50
Example
candies = [2, 3, 5, 1, 3], extraCandies = 3[true, true, true, false, true]Explanation The current max is 5. Adding 3 extra candies: kid 0 gets 5 (tied for max, true), kid 3 gets 4 (not max, false), and so on.
Find the max, then check each kid plus the extra
Scanning finds the current maximum: 5 (at index 2).
What happens in this step
candies = [2, 3, 5, 1, 3] maxCandies = 5
Steps to visualize
- Scan the array once to find the current maximum number of candies.
- For each kid, add extraCandies to their count.
- If that total is at least the current maximum, mark them true.
- Otherwise mark them false.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Scanning finds the current maximum: 5 (at index 2).
What happens in this step
candies = [2, 3, 5, 1, 3] maxCandies = 5
Solution
function kidsWithCandies(candies, extraCandies) {
const maxCandies = Math.max(...candies);
return candies.map((count) => count + extraCandies >= maxCandies);
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
candies = [2, 3, 5, 1, 3], extraCandies = 3 | [true, true, true, false, true] | example from the docstring |
candies = [4, 2, 1, 1, 2], extraCandies = 1 | [true, false, false, false, false] | extra candies too small for anyone but the current leader |
candies = [12, 1, 12], extraCandies = 10 | [true, false, true] | multiple kids already tied for the maximum |
candies = [1, 5], extraCandies = 1 | [false, true] | smallest valid input, exactly two kids |
candies = [5, 5, 5], extraCandies = 0 | [true, true, true] | every kid already has the same amount with zero extra needed to tie |
candies = [1, 1, 1], extraCandies = 50 | [true, true, true] | extra candies large enough that everyone ties for the maximum |