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]
- 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)