Sponsored
Sponsored
This approach iterates through each kid's candies and checks if adding the extraCandies
to their current candies makes them equal to or greater than the maximum number of candies present initially. It involves finding the maximum candies first and then performing this computation.
Time Complexity: O(n), where n is the number of kids.
Space Complexity: O(1), not counting the output array.
1function kidsWithCandies(candies, extraCandies) {
2 let maxCandies = Math.max(...candies);
3 return candies.map(candy => candy + extraCandies >= maxCandies);
4}
The solution determines the maximum number of candies using Math.max
combined with the spread operator. It then uses map
to create a new array based on the condition checking if each kid's candies with extras meet or exceed the maximum found.
This approach optimizes the process by combining the finding of the max candies and constructing the result array into a single pass by keeping track of the maximum with conditional updates.
Time Complexity: O(n)
Space Complexity: O(1) aside from the result.
1
In JavaScript, we efficiently find the maximum using the spread operator with Math.max
and build the return array within a single logical flow using map
.