Simply following above recursive formula .
for L in range ( 1 , n - 1 ) : NEW_LINE INDENT for i in range ( n - L ) : NEW_LINE INDENT dp [ i ] [ i + L ] = min ( dp [ i + 1 ] [ i + L ] + p [ i - 1 ] * p [ i ] * p [ i + L ] , dp [ i ] [ i + L - 1 ] + p [ i - 1 ] * p [ i + L - 1 ] * p [ i + L ] ) NEW_LINE DEDENT DEDENT return dp [ 1 ] [ n - 1 ] NEW_LINE