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.
1import java.util.ArrayList;
2import java.util.List;
3
4public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
5 int maxCandies = 0;
6 for (int candy : candies) {
7 maxCandies = Math.max(maxCandies, candy);
8 }
9 List<Boolean> result = new ArrayList<>();
10 for (int candy : candies) {
11 result.add(candy + extraCandies >= maxCandies);
12 }
13 return result;
14}
This Java solution traverses through the candies array twice: once to find the maximum, and then to populate the result list by checking each kid's potential maximum candy count after receiving extra candies.
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 C solution works within two concise passes, determining the maximum candies in the first loop and checking the condition for each child in the second loop without re-evaluating the maximum.