LC 1431. Kids With the Greatest Number of Candies

Sarthak Sehgal · May 2, 2020

This is a very straightforward greedy question. If we give all the candies to a kid and still the kid does not have the greatest number of candies then clearly the kid would never have greatest number of candies.

class Solution {
public:
    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
        int maxCandy = *max_element(candies.begin(), candies.end());

        vector<bool> res;
        for (int c : candies)
            if (c+extraCandies>=maxCandy)
                res.push_back(true);
            else
                res.push_back(false);

        return res;
    }
};

Time complexity: O(n)
Space complexity: O(1)

Twitter, Facebook