π§ Kids With the Greatest Number of Candies


πΉ Problem Summary:
Youβre given:
A vector
candies
, wherecandies[i]
is the number of candies thei-th
kid has.An integer
extraCandies
.
Task:
Return a boolean array
result
of the same length ascandies
.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
; elsefalse
.Note: Multiple kids can have the greatest number of candies.
π Example:
Input: candies = [1, 2, 3], extraCandies = 1
- Maximum current candies =
3
Kid | candies[i] + extraCandies | β₯ max (3)? | Result |
0 | 1 + 1 = 2 | β | false |
1 | 2 + 1 = 3 | β | true |
2 | 3 + 1 = 4 | β | true |
Output: [false, true, true]
π Approach:
Find the maximum number of candies any kid currently has.
Loop through each kidβs candies and:
Add the extra candies.
Compare with
maxVal
.Store
true
orfalse
in result vector.
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 π
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