[코딩테스트] 😀 이모티콘 행사 - Kakao2023

2025. 10. 7. 23:01알고리즘

문제링크

난이도

레벨 2 (1점)

유형

구현, BFS

소요시간

1시간

회고

문제 자체는 어렵지 않았으나, 소수점 계산에서 좀 헤맷다. 15, 16, 18 등의 케이스에서 실패했는데 알고보니, 부동소수점 처리를 에서 연산을 제대로 못하였다. 나누기 연산을 가장 뒤로 하여 오차를 줄였다.

 

// AS-IS
(Int((100.0 - Double(rate)) / 100.0 * origin, rate)
// TO-BE
(Int((100.0 - Double(rate)) * origin / 100.0), rate)

코드

var subscriptions = 0
var price = 0
var emoticonsCount = 0
var emotions = [Int]()
var userArray = [[Int]]()

func solution(_ users:[[Int]], _ emoticons:[Int]) -> [Int] {
    emoticonsCount = emoticons.count
    emotions = emoticons
    userArray = users

    combi()
    return [subscriptions, price]
}

func combi(_ index: Int = 0, _ selected: [Int] = []) {
    let dc = [10, 20, 30 ,40]

    if emoticonsCount == index {
        calc(selected)
        return
    }

    combi(index + 1, selected + [dc[0]])
    combi(index + 1, selected + [dc[1]])
    combi(index + 1, selected + [dc[2]])
    combi(index + 1, selected + [dc[3]])
}

func calc(_ selected: [Int]) {
    var localSubscribe = 0
    var localAcc = 0

    let discounted = selected.enumerated().map { (index, rate) in
        let origin = Double(emotions[index])
        return (Int((100.0 - Double(rate)) * origin / 100.0), rate)
    }

    for user in userArray {
        let thresholdRate = user[0]
        let thresholdPrice = user[1]

        var acc = 0

        discounted.forEach { price, rate in
            if rate < thresholdRate { return }
            acc += price
        }

        if acc >= thresholdPrice {
            acc = 0
            localSubscribe += 1
        }

        localAcc += acc
    }

    if subscriptions < localSubscribe {
        subscriptions = localSubscribe
        price = localAcc
    } else if subscriptions == localSubscribe {
        if subscriptions == 0 {
            if price < localAcc {
                price = localAcc
            }
        } else {
            price = max(price, localAcc)
        }
    }
}