Pattern: Array scan → find the max first, then compare
Difficulty: Easy
Time: O(n) | Space: O(n) for the output
Problem
Each kid has some candies. You have extraCandies to give to one kid.
For every kid, return true if giving them all the extra candies would make them have the most (ties count).
candies = [2,3,5,1,3], extraCandies = 3 → [true, true, true, false, true]
Core idea
Find the current max once. Then each kid only needs to reach it.
- Find the biggest pile →
max. - For each kid, check
candies[i] + extraCandies >= max.
You don’t need to compare every kid with every other kid. The only kid that matters is the one with the most.
Code (TypeScript)
function kidsWithCandies(candies: number[], extraCandies: number): boolean[] {
const max = Math.max(...candies);
return candies.map((c) => c + extraCandies >= max);
}Gotchas
- Use
>=, not>. Tying with the max still counts as “the greatest”. - Brute force (compare each kid with all others) is O(n²). One pass for the max makes it O(n).
Math.max(...arr)spreads the array into arguments. Fine here (n ≤ 100), but on huge arrays it can hit the argument limit. Then use a loop orreduce.- The kid who already has the max is always
true.
Pattern to remember
“Compare each item against the best one” → precompute the best once, then do one pass.
Same trick: running max/min, prefix sums, “find the max, then check each”.
Related
- Can Place Flowers (LC 605) is next in LeetCode 75