Dynamic Programming21 sections · 916 units
Open in Course

Tree Diameter - State Design

Deepest path down

dp[v]dp[v] = the length of the longest path starting at vv and going down into vv's subtree. For a leaf, dp[leaf]=0dp[\text{leaf}] = 0 (no edges going down).

For internal nodes, dp[v]=1+max(dp[child])dp[v] = 1 + \max(dp[\text{child}]) over all children. At each node vv, the longest path through vv combines the two deepest downward paths: dp[child1]+dp[child2]+2dp[\text{child}_1] + dp[\text{child}_2] + 2. Track this in a global variable as you go.