감자주먹밥

[LeetCode] 1431. Kids With the Greatest Number of Candies 본문

알고리즘

[LeetCode] 1431. Kids With the Greatest Number of Candies

JustHm 2023. 6. 22. 18:24
728x90

 

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/description/?envType=study-plan-v2&envId=leetcode-75 

 

Kids With the Greatest Number of Candies - LeetCode

Can you solve this real interview question? Kids With the Greatest Number of Candies - 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 extraCandie

leetcode.com

여분의 사탕을 각 아이들한테 다 줬을때, 그 아이가 가지고 있는 사탕이 제일 많으면 true 아니면 false로 배열을 만들어 리턴해주면 된다.

class Solution {
    func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {
        let max = candies.max()!
        var result: [Bool] = []
        for candy in candies {
            if max <= candy + extraCandies {
                result.append(true)
            } else { result.append(false) }
        }
        return result
    }
}

강제 언래핑시 오류는 일어날 일 없어보여서 그냥 해버렸다.

단계별로 해결했는데 다른 솔루션 중 재밋는 솔루션을 확인했다.

class Solution {
    func kidsWithCandies(_ candies: [Int], _ extraCandies: Int) -> [Bool] {
        let requiredCount = (candies.max() ?? 0) - extraCandies

        return candies.map({ $0 >= requiredCount })
    }
}

가장 많은 사탕 갯수와 여분의 사탕을 뺀 값을 가지고, 아이들이 가지고 있는 사탕이 이 값보다 적으면 가장 많은 사탕을 가질 수 없다는 걸 알 수 있다...

728x90
Comments