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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more