Leetcode 1431. Kids With the Greatest Number of Candies
You are given an array candies
where each candies[i]
represents the number of candies that the i-th
kid has. For each kid, check if they can have the greatest number of candies among all kids if they are given extraCandies
more.
Return a boolean array result
of length n
, where result[i]
is true
if, after giving the i-th
kid all the extraCandies
, they will have the greatest number of candies among all the kids, else false
.
Example:
Input: candies = [2, 3, 5, 1, 3], extraCandies = 3
Output: [true, true, true, false, true]
Constraints:
2 <= candies.length <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50
extraCandies
, and check if it is greater than or equal to the current maximum number of candies.Here is the C++ code to solve the problem:
#include <vector>
#include <algorithm> // For std::max_element
std::vector<bool> kidsWithCandies(std::vector<int>& candies, int extraCandies) {
// Find the maximum number of candies any kid currently has
int maxCandies = *std::max_element(candies.begin(), candies.end());
// Resultant boolean vector to store the result for each kid
std::vector<bool> result(candies.size(), false);
// Check for each kid
for (int i = 0; i < candies.size(); ++i) {
// If current kid's candies plus extraCandies is greater than or equal to maxCandies
if (candies[i] + extraCandies >= maxCandies) {
result[i] = true; // This kid can have the greatest number of candies
}
}
return result;
}
O(n)
, where n
is the number of elements in candies
.candies
array to check each kid’s condition takes O(n)
.Thus, the overall time complexity is O(n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?