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.
1using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<bool> KidsWithCandies(int[] candies, int extraCandies) {
int maxCandies = candies.Max();
List<bool> result = new List<bool>();
foreach (int candy in candies) {
result.Add(candy + extraCandies >= maxCandies);
}
return result;
}
}
In this C# solution, computing max using Max
is followed by a single pass to evaluate each kid's possible new candy count, ensuring clarity and efficiency in filling the result list.