Dare2Solve
The problem requires determining whether each child in an array of candies
can have the greatest number of candies if given a certain number of extra candies. The task is to return a list of boolean values where each value corresponds to whether a particular child can have the greatest number of candies after receiving the extra candies.
The intuition behind solving this problem is to first identify the current maximum number of candies that any child has. By adding the extra candies to each child's existing count, we can compare it against the maximum to determine if they can reach or exceed this maximum value.
True
in the result list; otherwise, mark False
.O(n)
, where n
is the number of children. This is because we iterate through the list of candies
twice—once to find the maximum value and once to generate the result list.
O(n)
, where n
is the number of children. The space is used to store the boolean result list.
class Solution {
public:
std::vector<bool> kidsWithCandies(std::vector<int>& candies, int extraCandies) {
int l = *std::max_element(candies.begin(), candies.end());
std::vector<bool> result;
for (int val : candies) {
result.push_back(val + extraCandies >= l);
}
return result;
}
};
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
l = max(candies)
return [(val + extraCandies) >= l for val in candies]
public class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int l = 0;
for (int candy : candies) {
l = Math.max(l, candy);
}
List<Boolean> result = new ArrayList<>();
for (int val : candies) {
result.add(val + extraCandies >= l);
}
return result;
}
}
var kidsWithCandies = function (candies, extraCandies) {
let l = Math.max(...candies)
return candies.map((val) => (val + extraCandies) >= l)
};