![]() |
VOOZH | about |
Given tree with N vertices rooted at node 0, edges given by array edges[][] and array arr[] of size N representing coins[] on each node. In one operation pick any node and collect all its coins. Task for this problem is to find maximum number of coins collected such that path sum from root node to any leaf node remains positive (path sum from root node to leaf node is total coins present on nodes of simple path between root to leaf).
Examples:
Input: N = 6, A[] = {5, 2, 5, 2, 1, 1 }, edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {2, 4}, {4, 5}}
Output: 11
Explanation: We can collect coins from node 1, 2, 3, 4 and 5. Total coins = 2 + 5 + 2 + 1 + 1 = 11.
Since root node 0 is non zero any path starting from root node to any leaf will be non zero.Input: N = 7, A[] = { 20, 10, 9, 7, 4, 3, 5 }, edges[][2] = { {0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6} }
Output: 40
Explanation: We can collect coins from nodes 0, 2, 3 and 4. Total coins = 20 + 9 + 7 + 4 = 40
- path sum from 0 to 4 is equal to 10.
- path sum from 0 to 3 is equal to 10.
- path sum from 0 to 5 is equal to 3.
- path sum from 0 to 6 is equal to 5.
So, path sum from root node 0 to any leaf is non-zero.
Approach: To solve the problem, follow the below idea:
Observation: We have two choices to make for every subtree root. Either we pick the coins present on root of subtree or all coins on present on its descendants. Problem is turned into other way around lets find minimum coins required to keep path sum from root node to any leaf node non-zero.
Tree Dynamic Programming can be used to solve this problem. The main concept of DP in the problem will be:
DP[v] will store minimum coins required so path sum from node v to any leaf node is non-zero.
Transition: dp[v] = min(A[v], ∑dp[ui])
Step-by-step algorithm:
Below is the implementation of the approach:
11
Time Complexity: O(N), where N is the number of nodes in the tree.
Auxiliary Space: O(N)