Kids With the Greatest Number of Candies - Problem

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the i-th kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the i-th kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

Input & Output

Example 1 — Basic Case
$ Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
💡 Note: Maximum is 5. Kid 0: 2+3=5≥5 ✓, Kid 1: 3+3=6≥5 ✓, Kid 2: 5+3=8≥5 ✓, Kid 3: 1+3=4<5 ✗, Kid 4: 3+3=6≥5 ✓
Example 2 — All Can Be Greatest
$ Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
💡 Note: Maximum is 4. Only kid 0: 4+1=5≥4 can be greatest. Others: 2+1=3<4, 1+1=2<4
Example 3 — Large Extra Candies
$ Input: candies = [12,1,12], extraCandies = 10
Output: [true,true,true]
💡 Note: Maximum is 12. Kid 0: 12+10=22≥12 ✓, Kid 1: 1+10=11<12 ✗, Kid 2: 12+10=22≥12 ✓

Constraints

  • 2 ≤ candies.length ≤ 100
  • 1 ≤ candies[i] ≤ 100
  • 1 ≤ extraCandies ≤ 50

Visualization

Tap to expand
Kids With the Greatest Number of Candies INPUT 2 Kid 0 3 Kid 1 5 Kid 2 1 Kid 3 3 Kid 4 candies array: 2 3 5 1 3 extraCandies = 3 (candies to give) candies = [2,3,5,1,3] extraCandies = 3 n = 5 kids ALGORITHM STEPS 1 Find Maximum max(candies) = 5 2 Loop Each Kid Check: candies[i]+3 >= 5? Kid Has +Extra >=5? 0 2 2+3=5 true 1 3 3+3=6 true 2 5 5+3=8 true 3 1 1+3=4 false 4 3 3+3=6 true 3 Build Result Store boolean for each kid 4 Return Array O(n) time, O(1) extra space FINAL RESULT 5 OK 2+3 6 OK 3+3 8 OK 5+3 4 NO 1+3 6 OK 3+3 max needed = 5 Output: [true,true,true,false,true] Comparison to max (5): Kid0: 5 >= 5 Kid1: 6 >= 5 Kid2: 8 >= 5 Kid3: 4 < 5 Kid4: 6 >= 5 4 out of 5 kids can have max! Key Insight: Find Max Once (Optimal) Instead of comparing each kid against all others (O(n^2)), find the maximum candies first in O(n). Then check if candies[i] + extraCandies >= maxCandies for each kid. Total: O(n) time, O(1) extra space. TutorialsPoint - Kids With the Greatest Number of Candies | Optimal - Find Max Once
Asked in
Microsoft 15 Amazon 12
125.0K Views
Medium Frequency
~10 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen