Problem Description
There are n kids with candies.
You are given an integer array candies, where candies[i] is the number of candies the i-th kid has,
and an integer extraCandies, the number of extra candies you have.
Return an array result of length n, where result[i] is true if, after giving the i-th kid all
the extra candies, they will have the greatest number of candies among all kids, or false otherwise.
Note that multiple kids can have the greatest number of candies at the same time.
Constraints
- The length of
candiesis in the range from 1 to 100 - Each kid has at least 1 and at most 100 candies
extraCandiesis in the range from 1 to 50
Examples
Input: candies = [2,3,5,1,3], extraCandies = 3
Answer: [true,true,true,false,true]
Solution
We can find the maximum number of candies among all kids and then check whether a particular kid's count
reaches that maximum after adding extraCandies to it.
export const kidsWithCandies = (candies: number[], extraCandies: number): boolean[] => {
let res: boolean[] = [];
const maxCandies = Math.max(...candies);
candies.forEach((count) => {
res.push(count + extraCandies >= maxCandies);
});
return res;
};Complexity Analysis
Time Complexity
To find the answer we iterate over the array twice, i.e. perform 2n operations.
The overall time complexity is O(n).
Space Complexity
The space complexity is linear: O(n), since we create an array of length n to store the answer.