Sponsored
Sponsored
This approach iterates through each kid's candies and checks if adding the extraCandies
to their current candies makes them equal to or greater than the maximum number of candies present initially. It involves finding the maximum candies first and then performing this computation.
Time Complexity: O(n), where n is the number of kids.
Space Complexity: O(1), not counting the output array.
1#include <vector>
2
3std::vector<bool> kidsWithCandies(std::vector<int>& candies, int extraCandies) {
4 int maxCandies = *max_element(candies.begin(), candies.end());
5 std::vector<bool> result(candies.size());
6 for (int i = 0; i < candies.size(); i++) {
7 result[i] = (candies[i] + extraCandies >= maxCandies);
8 }
9 return result;
10}
The solution uses max_element
from the STL to find the maximum number of candies. It then checks, for each kid, if giving them the extra candies will make their new candy count equal to or greater than the maximum.
This approach optimizes the process by combining the finding of the max candies and constructing the result array into a single pass by keeping track of the maximum with conditional updates.
Time Complexity: O(n)
Space Complexity: O(1) aside from the result.
1
This Java solution first computes the maximum number of candies and directly builds the result list by evaluating each candy count with added extraCandies in a second loop, achieving a one-pass calculation result.