easy

Kids With the Greatest Number of Candies

Check which kids could have the most candies after a bonus.

1. Define the problem

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

Inputcandies = [2, 3, 5, 1, 3], extraCandies = 3
Output[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.

2. Visualize the solution

Find the max, then check each kid plus the extra

Find the max, then check each kid plus the extra
Statusinit

Scanning finds the current maximum: 5 (at index 2).

What happens in this step

candies = [2, 3, 5, 1, 3]
maxCandies = 5
Step 1 of 4

Steps to visualize

  1. Scan the array once to find the current maximum number of candies.
  2. For each kid, add extraCandies to their count.
  3. If that total is at least the current maximum, mark them true.
  4. Otherwise mark them false.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Find the max, then check each kid plus the extra
Statusinit

Scanning finds the current maximum: 5 (at index 2).

What happens in this step

candies = [2, 3, 5, 1, 3]
maxCandies = 5
Step 1 of 4
4. Solution

Solution

solution.tsTypeScript
function kidsWithCandies(candies, extraCandies) {
  const maxCandies = Math.max(...candies);

  return candies.map((count) => count + extraCandies >= maxCandies);
}
Time
O(n)
Space
O(n)
5. Test cases

Test cases

InputExpectedCovers
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