728x90
https://school.programmers.co.kr/learn/courses/30/lessons/150368
블라인드 테스트땐 이 문제를 왜 못 풀었을까.. 내가 발전한 건지 아니면 전이 너무 부족했던 건지..^^
우선 이모티콘마다 할인율을 정해주면 된다. 여기서 주의할 것은 하나의 할인율이 여러 이모티콘에 적용될 수 있다는 것! 즉, 중복 순열~ BT를 통해 중복 순열을 정해주고(combination), calculate 함수를 통해 결과값을 계산해 줬다.
- 이모티콘 매출액(amount)
- 서비스 가입 수(account)
- 사용자를 한 명씩 순회하면서 각 이모티콘의 할인율을 보고 구매할지 결정
→ 사용자 할인율보다 크거나 같은 이모티콘만 구매
- sum에 구매한 이모티콘의 가격 합 누적.
- 모든 이모티콘을 확인했다면, 서비스에 가입할지 확인.
- 만약 유저의 기준 금액보다 크거나 같다면 플러스 가입 아니면 amount에 sum 더하기
모든 사용자에 대해서 완료했다면, 조건 우선순위에 따라 정렬해 주고 첫 번째 원소를 배열 형태로 출력
- 가입자를 최대한 늘리는 것
- 판매액을 최대한 늘리는 것
[전체 코드]
import Foundation
var rate = [10, 20, 30, 40]
var combination = [Int]()
var n = 0 //이모티콘 개수
var result = [(Int, Int)]()
//만든 경우에 따른 결과값 계산
func calculate(_ users: [[Int]], _ emoticons: [Int]) -> (Int, Int) {
var amount = 0 //이모티콘 매출액
var account = 0 //서비스 가입수
for user in users {
var sum = 0
for i in 0..<emoticons.count {
if combination[i] >= user[0] { //사용자 할인율보다 큰 이모티콘만 구매
sum += emoticons[i] - Int(Double(emoticons[i]) * Double(combination[i]) / 100.0)
}
}
if sum >= user[1] { account += 1 } //이모티콘 플러스 가입
else { amount += sum }
}
return (account, amount)
}
//각 이모티콘에 대한 할인율 순열 구하기(중복가능)
func bt(_ now: Int, _ users: [[Int]], _ emoticons: [Int]) {
if now == n {
result.append(calculate(users, emoticons))
return
}
for i in 0..<rate.count {
combination.append(rate[i])
bt(now+1, users, emoticons)
combination.removeLast()
}
}
func solution(_ users:[[Int]], _ emoticons:[Int]) -> [Int] {
n = emoticons.count
bt(0, users, emoticons)
result = result.sorted(by: { $0.0 == $1.0 ? $0.1 > $1.1 : $0.0 > $1.0 })
return [result[0].0, result[0].1]
}
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Swift] 덧칠하기 (0) | 2023.03.26 |
---|---|
[프로그래머스/Swift] 택배 배달과 수거하기 (0) | 2023.03.25 |
[프로그래머스/Swift] 둘만의 암호 (0) | 2023.02.12 |
[프로그래머스/Swift] k진수에서 소수 개수 구하기 (0) | 2023.01.15 |
[프로그래머스/Swift] 점프와 순간 이동 (0) | 2023.01.15 |