This is the 3rd problem in Leetcode75 ( Array&Hashing ).
Problem Statement
There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.
Note that multiple kids can have the greatest number of candies.
Solution Strategy
- Create an array of boolean, we're going to store the result here
- Find the current maximum number of candies
- Iterate through the array of candies. For each candy, add the extra candies and check if this addition makes it the greatest. If so, append true to the results array; otherwise, append false
class Solution {
func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {
var result = [Bool]()
let greatestCandies = candies.max()
guard let greatestCandies = greatestCandies else {
fatalError("error")
}
for candy in candies {
if candy + extraCandies >= greatestCandies {
result.append(true)
} else {
result.append(false)
}
}
return result
}
}
## SOLUTION 2 ##
if you are familiar with .map() function, you could do it like this
func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {
guard let maxCandies = candies.max() else { return [] }
return candies.map { candy in
candy + extraCandies >= maxCandies
}
}
Top comments (0)