The solution consists of two DFS, first DFS is to calculate subi: the max difference of the subgraph in subtree of i. Note that we treat the graph as a rooted tree, so the subtree means the part that is lower than node i. This is pretty naive DFS.
The second dfs is to find the answer of each vertex. Since we only considered the contribution of the subtree, we need to add the contribution of other part the graph. How to find this contribution? We always get the answer of higher nodes first. Let v be the children of node i, if subv>0, the contribution is ansi−subv since we don’t want to count the contribution of subtree twice. If subv≤0, we don’t need to subtract subv since we didn’t count it in ansi. If ansi−subv<0, it’s useless for ansv. Thus, the contribution of other part is max(ansi−max(subv,0),0).