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 <stdbool.h>
2
3void kidsWithCandies(int* candies, int candiesSize, int extraCandies, bool* result) {
4 int maxCandies = 0;
5 for (int i = 0; i < candiesSize; i++) {
6 if (candies[i] > maxCandies) {
7 maxCandies = candies[i];
8 }
9 }
10 for (int i = 0; i < candiesSize; i++) {
11 result[i] = (candies[i] + extraCandies >= maxCandies);
12 }
13}
The solution begins by finding the current maximum number of candies in the array candies
. Then, it iterates through each kid's candies, adding extraCandies
and comparing the sum to the maximum. If the sum is greater than or equal to the maximum, true
is stored in the result, otherwise false
is stored.
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;
2using 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.