Home
DSA Patterns
Greedy Algorithms
Kids With the Greatest Number of Candies
Kids With the Greatest Number of Candies
Decide for each kid whether receiving every extra candy would give them the most candies, by finding the current maximum once and comparing each kid to it.
Problem Understanding
Kids With the Greatest Number of Candies (LeetCode 1431): candies[i] is how many candies kid i has, and you have extraCandies to give. For each kid, return true if giving them all the extra candies would leave them with the greatest number of candies among all the kids (ties allowed), and false otherwise.
Examples: [2, 3, 5, 1, 3], extra 3 → [true, true, true, false, true]; [12, 1, 12], extra 10 → [true, false, true].
The Intuition: Only the Biggest Pile Matters
To have the most candies, a kid only needs to match the largest pile; everyone smaller is beaten automatically.
- Find the maximum in one pass.
- Check each kid: can candies[i] + extraCandies reach it?
Precomputing one summary value so each question becomes O(1) is the same move as Find Pivot Index, which precomputes the total.
Interactive Walkthrough
EXTRA = 3 · BAR = MAX
FIND THE MAX
candies
0
1
max
2
3
4
result
max
5
candies + extra
:
Kids who can
0
The most any kid has now is 5. That is the bar each kid must reach with all 3 extra candies
Next
Kid 0: 2 + 3 = 5 ≥ 5, so true
candies
extra
The kids holding the maximum are outlined: that is the bar. Each kid is checked in turn and the result row fills in with T or F. Try Example 3, where two kids share the maximum.
Dry Run Table
Input: candies = [2, 3, 5, 1, 3], extraCandies = 3. The maximum is 5.
| Kid | candies + 3 | ≥ 5? |
|---|---|---|
| 0 | 5 | true |
| 1 | 6 | true |
| 2 | 8 | true |
| 3 | 4 | false |
| 4 | 6 | true |
Answer: [true, true, true, false, true].
The Solution Template
Two passes: one for the maximum, one to compare.
Kids With the Greatest Number of Candies Code
1var kidsWithCandies = function(candies, extraCandies) {2 const most = Math.max(...candies);3 return candies.map((c) => c + extraCandies >= most);4};
Edge Cases & Common Mistakes
- Ties: use ≥, not >; reaching the maximum exactly counts.
- Recomputing the max per kid: turns O(n) into O(n²).
- Adding the extra candies to everyone: only the kid being checked receives them.
Summary
Find the maximum once, then answer each kid with candies[i] + extraCandies ≥ max. O(n) time, O(1) extra space.
More practice: DSA interview questions with answers · patterns cheat sheet
