April 27, 2021
트리를 순회하며 각 구성원이 받을 돈을 계산하는 문제
쉽게 쓱싹할 줄 알았는데 생각보다 고전했다.
function solution(enroll, referral, seller, amount) {
const tree = {}
tree['-'] = { parent: null, reward: 0 }
for (let i = 0; i < enroll.length; i++)
tree[enroll[i]] = { parent: referral[i], reward: 0 }
const bottomUp = (name, reward) => {
const current = tree[name]
if (!reward || !current.parent) return
const rewardForParent = Math.floor(reward / 10)
current.reward += reward - rewardForParent
bottomUp(current.parent, rewardForParent)
}
for (let i = 0; i < seller.length; i++) {
bottomUp(seller[i], amount[i] * 100)
}
return enroll.map(name => tree[name].reward)
}
const tree = {}
tree['-'] = { parent: null, reward: 0 }
for (let i = 0; i < enroll.length; i++)
tree[enroll[i]] = { parent: referral[i], reward: 0 }
각 구성원이 가져간 돈의 10%를 추천인이 가져간다.
const bottomUp = (name, reward) => {
const current = tree[name]
if (!reward || !current.parent) return
const rewardForParent = Math.floor(reward / 10)
current.reward += reward - rewardForParent
bottomUp(current.parent, rewardForParent)
}
for (let i = 0; i < seller.length; i++) {
bottomUp(seller[i], amount[i] * 100)
}
enroll의 순서에 맞게 각 회원이 가진 돈을 반환한다.
return enroll.map(name => tree[name].reward)