One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed
for r in range ( i , j + 1 ) : NEW_LINE INDENT cost = ( optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ) NEW_LINE if cost < Min : NEW_LINE INDENT Min = cost NEW_LINE DEDENT DEDENT