Kids With the Greatest Number of Candies
(#1431), Easy
Category: Array
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
Simple Loop with Math.max
- Find the maximum candy count using `Math.max(...candies)`.
- Loop through each kid in the `candies` array.
- For each kid, check if `candies[i] + extraCandies >= maxCandies`.
- If the condition is true, store `true` at that index; otherwise, store `false`.
- Return the resulting boolean array.
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)