Understanding the Greedy Approach: Can Kids Have Maximum Candies?
In this problem, you are given an array of integers candies
, where candies[i]
represents the number of candies that the ith
kid has, and an integer extra_candies
, representing the number of extra candies that you have.
The task is to find out if you distribute the extra candies among the kids, can a kid have the greatest number of candies among them? A kid can only have one extra candy at a time.
The input is an array of integers candies
and an integer extra_candies
.
The output is an array of boolean values, where True
means the kid could have the maximum number of candies if they receive the extra candies, and False
means otherwise.
The base case for this problem is when the input array candies
is nil
or empty. If there are no kids, no computation is needed and we simply return without doing any computation.
The provided solution uses a greedy approach to solve the problem. In the context of this problem, a greedy approach means to always give the extra candy to the kid who can thereby achieve the maximum number of candies.


The function kids_with_candies
first calculates the maximum number of candies that any kid currently has. Then, for each kid, it checks if giving that kid the extra candies will allow them to have at least as many candies as the current maximum. If yes, it adds True
to the result array, and if no, it adds False
.
This is done using the Ruby expression (candy + extra_candies >= max)
, which will evaluate to either True
or False
.
Finally, the function returns the result array, which shows for each kid whether or not they could have the maximum number of candies by receiving the extra candies. This greedy approach is efficient and solves the problem in a linear time complexity, making it suitable for large inputs.
Reading the explanation of the output was a bit scary. After looking at the hint, it was easy to code the solution because the condition to check was expressed directly in the code.
The input and output are:
@param {Integer[]} candies
@param {Integer} extra_candies
@return {Boolean[]}
The base case is when the input is nil. This can happen when the input to the program is nil or when we reach the leaf node (it has no children, nothing to compute). We return without doing any computation.
Greedy Approach

