Kids With the Greatest Number of Candies

easy array greedy

Problem

Given the array treats and the integer extra, where treats[i] represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extra candies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.

Inputtreats = [4, 2, 7, 1], extra = 3
Output[true, false, true, false]
Max is 7. With +3 extras: 7, 5, 10, 4 → ≥7? true, false, true, false.

def kids_with_candies(treats, extra):
    top = max(treats)
    return [t + extra >= top for t in treats]
function kidsWithCandies(treats, extra) {
  const top = Math.max(...treats);
  return treats.map(t => t + extra >= top);
}
class Solution {
    public List<Boolean> kidsWithCandies(int[] treats, int extra) {
        int top = 0;
        for (int t : treats) if (t > top) top = t;
        List<Boolean> ans = new ArrayList<>();
        for (int t : treats) ans.add(t + extra >= top);
        return ans;
    }
}
vector<bool> kidsWithCandies(vector<int>& treats, int extra) {
    int top = *max_element(treats.begin(), treats.end());
    vector<bool> ans;
    for (int t : treats) ans.push_back(t + extra >= top);
    return ans;
}
Time: O(n) Space: O(n) for the result