VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-coins-such-that-root-to-leaf-path-sum-is-positive/

⇱ Maximum coins such that root to leaf path sum is positive - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum coins such that root to leaf path sum is positive

Last Updated : 23 Jul, 2025

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:

  • Declaring Adjacency list adj[N] and fill the adjacency list by iterating on N - 1 edges.
  • Declaring DP[] array of length N.
  • Declare dfs function which takes two parameters as input v node and p its parent.
    • Iterate over all child's u and find out dp[v] = ∑dp[ui]
    • base case if v is not zero and there is only one element present in adjacent of v then update dp[v] as A[v]
    • otherwise update dp[v] = min(dp[v], A[v])
  • Call dfs(0, -1) function which is called for node 0 and its parent being -1
  • Declare variable totalCoins which has sum of all coins present on every node of v
  • Return totalCoins - dp[0]

Below is the implementation of the approach:


Output
11

Time Complexity: O(N), where N is the number of nodes in the tree.
Auxiliary Space: O(N)

Comment