Intuition
To determine which children can have the greatest number of candies after receiving extra candies, we first need to know the maximum number of candies that any child currently has. Then we can check for each child whether their current candies plus the extra candies are at least equal to that maximum.
Approach
- Find the maximum value in the
candiesarray to determine the current highest candy count. - Iterate over the
candiesarray again and for each child, check if their candies plusextraCandiesis greater than or equal to the maximum. - Push
trueorfalseto the result array based on the condition. - Return the result array.
Complexity
-
Time complexity:
$$O(n)$$ β We iterate through the list twice: once to find the max, and once to compare each childβs total. -
Space complexity:
$$O(n)$$ β We use an additional array of the same length to store the boolean results.
Code
export function kidsWithCandies(
candies: number[],
extraCandies: number
): boolean[] {
const result: boolean[] = [];
let highestCandy = candies[0];
// Find the maximum candy count
for (let i = 1; i < candies.length; i++) {
if (candies[i] > highestCandy) {
highestCandy = candies[i];
}
}
// Determine if each child can reach or exceed the max
for (let i = 0; i < candies.length; i++) {
const totalCandies = candies[i] + extraCandies;
result.push(totalCandies >= highestCandy);
}
return result;
}
NOTE: Itβs a very basic way to solve this problem you can make it short.