(This question has been seen in the interviews of the following companies: Google)
Given a tree with n nodes. Each node has k coins, where 0 <= k <= n . There are total n coins on the tree.
The goal is to move the coins such that each node has exactly one coin. What's the minimum moves required?
Each move can only move one coin to an adjacent node.
int moveCoins(TreeNode root) {
return dfs(root, new HashMap<>());
}
int dfs(TreeNode n, Map count) {
if(!count.containsKey(n)) {
count.put(n, n.val);
}
int coinsNum = count.get(n);
int res = 0;
for(TreeNode kid : n.children) {
res += dfs(kid, count);
coinsNum += count.get(kid);
res += Math.abs(count.get(kid));
}
count.put(n, coinsNum - 1);
return res;
}
Get one-to-one training from Google Facebook engineers
Top-notch Professionals
Learn from Facebook and Google senior engineers interviewed 100+ candidates.
Most recent interview questions and system design topics gathered from aonecode alumnus.
One-to-one online classes. Get feedbacks from real interviewers.
Customized Private Class
Already a coding expert? - Advance straight to hard interview topics of your interest.
New to the ground? - Develop basic coding skills with your own designated mentor.
Days before interview? - Focus on most important problems in target company question bank.