Dynamic Programming21 sections · 916 units
Open in Course

Optimal BST - The DP

State and transition

dp[i][j]dp[i][j] = minimum cost for keys ii to jj. Choose key kk as root. Left subtree: [i,k1][i, k-1]. Right subtree: [k+1,j][k+1, j]. All keys go one level deeper. dp[i][j]=minikj(dp[i][k1]+dp[k+1][j])+l=ijfldp[i][j] = \min_{i \leq k \leq j}(dp[i][k-1] + dp[k+1][j]) + \sum_{l=i}^{j} f_l The sum adds depth cost for all keys in the range.

Work through examples by hand before coding. Understanding the pattern makes implementation simple. Practice with similar problems to reinforce your understanding.