DEV Community

Dwiki
Dwiki

Posted on

Leetcode75 - Kids with the Greatest Number of Candies #3

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

  1. Create an array of boolean, we're going to store the result here
  2. Find the current maximum number of candies
  3. 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
    } 
}
Enter fullscreen mode Exit fullscreen mode

## 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
    }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay