πŸ§’ Kids With the Greatest Number of Candies

Abhinav KumarAbhinav Kumar
2 min read

πŸ”Ή Problem Summary:

You’re given:

  • A vector candies, where candies[i] is the number of candies the i-th kid has.

  • An integer extraCandies.

Task:

  • Return a boolean array result of the same length as candies.

  • For each kid, add extraCandies to their current candies.

  • If the new total is greater than or equal to the maximum among all kids, set result[i] = true; else false.

  • Note: Multiple kids can have the greatest number of candies.


πŸ“Œ Example:

Input: candies = [1, 2, 3], extraCandies = 1
  • Maximum current candies = 3
Kidcandies[i] + extraCandiesβ‰₯ max (3)?Result
01 + 1 = 2❌false
12 + 1 = 3βœ…true
23 + 1 = 4βœ…true

Output: [false, true, true]


πŸ” Approach:

  1. Find the maximum number of candies any kid currently has.

  2. Loop through each kid’s candies and:

    • Add the extra candies.

    • Compare with maxVal.

    • Store true or false in result vector.

  3. Return the result vector.


βœ… Final Code (LeetCode-style only):

class Solution {
public:
    vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
        int maxVal = *max_element(candies.begin(), candies.end());
        vector<bool> res;
        for (int candy : candies) {
            res.push_back(candy + extraCandies >= maxVal);
        }
        return res;
    }
};

🧠 Quick Note on max_element:

To find the maximum candies:

int maxVal = *max_element(candies.begin(), candies.end());
  • max_element (from <algorithm>) returns an iterator to the largest element.

  • We use * to dereference and get the value.

  • Time complexity: O(n)


keep coding keep optimising πŸš€

0
Subscribe to my newsletter

Read articles from Abhinav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abhinav Kumar
Abhinav Kumar

πŸŽ“ B.Tech CSE | πŸ‘¨β€πŸ’» Learning DSA & C++ | πŸš€ Building projects & writing what I learn | πŸ“š Currently solving LeetCode & exploring Git/GitHub