알고리즘/Leetcode

[leetcode/kotlin] 575.Distribute Candies

llollhh_ 2021. 3. 16. 23:24

문제링크

leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3657/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

답안 1)

/**
 candyType / 2를 하여 먹을 수 있는 사탕 갯수를 구한다.
 candyType을 Set으로 바꿔 중복을 제거한다.
 반복문을 돌며 사탕 타입을 확인했거나 먹을 수 있는 사탕의 갯수가 없으면 종료한다.
*/

import java.lang.Math

class Solution {
    fun distributeCandies(candyType: IntArray): Int {
        var edibleCount = candyType.size / 2
        var eatenCount = 0
        
        val candySetSize = candyType.toSet().size
        
        for (i in 0 until candySetSize) {
            if (edibleCount <= 0) break
            
            edibleCount -= 1
            eatenCount += 1
        }
        
        return eatenCount
    }
}

답안 2)

import java.lang.Math

class Solution {
    fun distributeCandies(candyType: IntArray): Int {
        var edibleCount = candyType.size / 2
        val candySetSize = candyType.toSet().size
        
        return Math.min(candySetSize, edibleCount)
    }
}