Kids With the Greatest Number of Candies(#1431)

Category: Array, Foundation

๐Ÿงฉ Problem Statement

There are n kids with candies. You're given an integer array `candies`, where `candies[i]` represents the number of candies the i-th kid has, and an integer `extraCandies`, which denotes the number of extra candies you have. Return a boolean array result of length n, where `result[i]` is true if, after giving all the extra candies to the i-th kid, they will have the greatest number of candies among all kids (or at least equal to the max).

๐Ÿ“š Examples

Input: candies = [2,3,5,1,3], extraCandies = 3

Output: [true,true,true,false,true]

Explanation:
  • The max candy count is 5. After giving 3 extra candies:
  • Kid 0: 2 + 3 = 5 โ†’ true
  • Kid 1: 3 + 3 = 6 โ†’ true
  • Kid 2: 5 + 3 = 8 โ†’ true
  • Kid 3: 1 + 3 = 4 โ†’ false
  • Kid 4: 3 + 3 = 6 โ†’ true

๐Ÿง  Approach

Approach: Loop + Math.max

โ€ข Use `Math.max(...candies)` to find the current max candy count.

โ€ข Loop through each kid and check if `candies[i] + extraCandies >= max`.

โ€ข Replace each element in the candies array with true or false based on this condition.

โ€ข Return the updated array.

This method is concise and leverages built-in JavaScript features.

๐Ÿ’ป Code

var kidsWithCandies = function(candies, extraCandies) {
    let maxCandies = Math.max(...candies);
    for (let i = 0; i < candies.length; i++) {
        candies[i] = candies[i] + extraCandies >= maxCandies;
    }
    return candies;
};

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(1) (excluding output array)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources